Mybatis註解開發

參考文章:mybatis註解開發html

 

環境搭建:

1.導入maven依賴:java

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>cn.mybatis.AnnotationDevelopment</groupId>
    <artifactId>TestPro</artifactId>
    <version>1.0-SNAPSHOT</version>

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.objectweb.asm/org.objectweb.asm -->
    <dependency>
        <groupId>org.objectweb.asm</groupId>
        <artifactId>org.objectweb.asm</artifactId>
        <version>3.3.1.v201105211655</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/cglib/cglib -->
    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib</artifactId>
        <version>3.2.8</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache-core -->
    <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache-core</artifactId>
        <version>2.6.11</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.javassist/javassist -->
    <dependency>
        <groupId>org.javassist</groupId>
        <artifactId>javassist</artifactId>
        <version>3.23.1-GA</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/junit/junit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/log4j/log4j -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.11.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.11.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.6</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
    <dependency>
        <groupId>org.mybatis.caches</groupId>
        <artifactId>mybatis-ehcache</artifactId>
        <version>1.1.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.12</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.8.0-beta2</version>
        <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.8.0-beta2</version>
    </dependency>

</dependencies>
</project>
pom.xml

2.數據庫信息:mysql

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=root
db.properties

3.編寫日誌配置文件web

log4j.rootLogger=DEBUG,stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t]  -  %m%n
log4j.xml

4.編寫配置文件:SqlMapConfig.xmlsql

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <properties resource="db.properties"></properties>
    <settings>
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"/>
        <setting name="cacheEnabled" value="true"></setting>
    </settings>
    <typeAliases><!--別名-->
        <!--<typeAlias type="xin.mikey.www.entity.User" alias="user"></typeAlias>-->
        <package name="xin.mikey.www.pojo"></package>

    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"></property>
                <property name="url" value="${jdbc.url}"></property>
                <property name="username" value="${jdbc.username}"></property>
                <property name="password" value="${jdbc.password}"></property>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--<mapper resource="sqlmap/User.xml"></mapper>-->
        <!--<mapper resource="mapper/UserMapper.xml"></mapper>-->
        <!--Mapper接口和映射文件必須在同一文件夾下  遵循規範
        <mapper class="xin.mikey.www.mapper.UserMapper"></mapper>-->
        <!--Mapper接口的包名,自動掃描。遵循規範
        <package name=""></package>-->
        <package name="xin.mikey.www.mapper"></package>
        <package name="xin.mikey.www.pojo"></package>
    </mappers>

</configuration>
SqlMapConfig.xml

5.編寫pojo類和Mapper接口數據庫

package xin.mikey.www.mapper;

import org.apache.ibatis.annotations.*;
import xin.mikey.www.pojo.User;

/**
 * @author Mikey
 * @Title:
 * @Description:
 * @date 2018/10/21 17:24
 * @Version 1.0
 */
@Mapper
public interface UserMapper {
    @Select("select * from user where id=#{id}")
    public User getUserById(Integer id);

    @Delete("delete from user where id=#{id}")
    public void deleteUserById(Integer id);

    @Insert("insert user(id,username,birthday,sex,address) value(#{id},#{username},#{birthday},#{sex},#{address})")
    public void addUser(User user);

    @Update("update user set id=#{id},username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}")
    public void updateUser(User user);
}
UserMapper
package xin.mikey.www.pojo;

import java.util.Date;

/**
 * @author Mikey
 * @Title:
 * @Description:
 * @date 2018/10/21 17:23
 * @Version 1.0
 */
public class User {
    private int id;
    private String username;
    private Date birthday;
    private Integer sex;
    private String address;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Date getBirthday(Date date) {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", birthday=" + birthday +
                ", sex=" + sex +
                ", address='" + address + '\'' +
                '}';
    }
}
User

6.編寫測試類apache

package xin.mikey.www.Test;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
import xin.mikey.www.mapper.UserMapper;
import xin.mikey.www.pojo.User;

import java.io.InputStream;
import java.util.Date;

import static org.junit.Assert.*;

/**
 * @author Mikey
 * @Title:
 * @Description:
 * @date 2018/10/21 19:42
 * @Version 1.0
 */
public class UserMapperTest {
    SqlSessionFactory sqlSessionFactory;
//    UserMapper userMapper;
    @Before
    public void setUp() throws Exception {
        InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        //初始化mybatis,建立SqlSessionFactory類的實例
        sqlSessionFactory =  new SqlSessionFactoryBuilder().build(resourceAsStream);
//        SqlSession sqlSession=sqlSessionFactory.openSession();
//        userMapper=sqlSession.getMapper(UserMapper.class);

    }

    @Test
    public void getUserById() {
        SqlSession sqlSession=sqlSessionFactory.openSession();
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        User userById = userMapper.getUserById(10);
        System.out.println("Message="+userById);
    }

    /**
     * delete User
     */
    @Test
    public void deleteUserById() {
        SqlSession sqlSession=sqlSessionFactory.openSession();
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        userMapper.deleteUserById(26);
    }

    @Test
    public void addUser() {
        SqlSession sqlSession=sqlSessionFactory.openSession();
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        User user=new User();
        user.setId(30);
        user.setUsername("奔波兒灞");
        user.setBirthday(new Date());
        user.setAddress("安徽");
        userMapper.addUser(user);
        sqlSession.commit();
    }

    @Test
    public void updateUser() {
        SqlSession sqlSession=sqlSessionFactory.openSession();
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        User userById = userMapper.getUserById(1);
        userById.setBirthday(new Date());
        userById.setAddress("廣西柳州");
        userMapper.updateUser(userById);
        sqlSession.commit();
    }
}
UserMapperTest

資料:

MyBatis能夠利用SQL映射文件來配置,也能夠利用Annotation來設置。MyBatis提供的一些基本註解以下表所示。api

 

註解數組

目標緩存

相應的XML

描述

@CacheNamespace

<cache>  

爲給定的命名空間(好比類)配置緩存。屬性:

implemetation,eviction,

flushInterval , size 和 readWrite 。

@CacheNamespaceRef

<cacheRef>

參照另一個命名空間的緩存來使用。

屬性:value,也就是類的徹底限定名。

@ConstructorArgs

方法

<constructor>

收集一組結果傳遞給對象構造方法。

屬性:value,是形式參數的數組

@Arg

方法

<arg>

<idArg>

 

單獨的構造方法參數,是ConstructorArgs  集合的一部分。屬性:id,column,javaType,typeHandler。

id屬性是布爾值,來標識用於比較的屬性,和<idArg>XML 元素類似

@TypeDiscriminator

方法

<discriminator>

一組實例值被用來決定結果映射的表

現。屬性:Column, javaType ,  jdbcType typeHandler,cases。

cases屬性就是實例的數組。

@Case

方法

<case>

單獨實例的值和它對應的映射。屬性:value  ,type ,results 。

Results 屬性是結果數組,所以這個註解和實際的ResultMap 很類似,由下面的  Results註解指定

@Results

方法

<resultMap>

結果映射的列表,包含了一個特別結果

列如何被映射到屬性或字段的詳情。

屬性:value ,是Result註解的數組

@Result

方法

<result>

<id>

在列和屬性或字段之間的單獨結果映

射。屬性:id ,column , property,

javaType ,jdbcType ,type Handler ,

one,many。id 屬性是一個布爾值,表

示了應該被用於比較的屬性。one屬性是單獨的聯繫,和 <association> 類似,而many 屬性是對集合而言的,和

<collection>類似。

@One

方法

<association>  

複雜類型的單獨屬性值映射。屬性:

select,已映射語句(也就是映射器方

法)的徹底限定名,它能夠加載合適類

型的實例。注意:聯合映射在註解API

中是不支持的。

@Many

方法

<collection>

複雜類型的集合屬性映射。屬性:

select,是映射器方法的徹底限定名,它可加載合適類型的一組實例。注意:聯合映射在 Java註解中是不支持的。

@Options

方法

映射語句的屬性

這個註解提供訪問交換和配置選項的寬廣範圍,它們一般在映射語句上做爲屬性出現。而不是將每條語句註解變複雜,Options 註解提供連貫清晰的方式來訪問它們。屬性:useCache=true,

flushCache=false,

resultSetType=FORWARD_ONLY,

statementType=PREPARED,

fetchSize= -1,timeout=-1 ,

useGeneratedKeys=false ,

keyProperty=」id「。

理解Java 註解是很重要的,由於沒有辦法來指定「null 」做爲值。所以,一旦你使用了 Options註解,語句就受全部默認值的支配。要注意什麼樣的默認值來避免不指望的行爲

@Insert

@Update

@Delete

方法

<insert>

<update>

<delete>

這些註解中的每個表明了執行的真實 SQL。它們每個都使用字符串數組(或單獨的字符串)。若是傳遞的是字符串數組,它們由每一個分隔它們的單獨空間串聯起來。屬性:value,這是字符串數組用來組成單獨的SQL語句

@InsertProvider

@UpdateProvider

@DeleteProvider

@SelectProvider

方法

<insert>

<update>

<delete>

<select>

容許建立動態

SQL。

這些可選的SQL註解容許你指定一個

類名和一個方法在執行時來返回運行

的SQL。基於執行的映射語句, MyBatis

會實例化這個類,而後執行由 provider

指定的方法. 這個方法能夠選擇性的接

受參數對象做爲它的惟一參數,可是必

須只指定該參數或者沒有參數。屬性:

type,method。type 屬性是類的徹底限定名。method  是該類中的那個方法名。

@Param

參數

N/A

當映射器方法需多個參數,這個註解能夠被應用於映射器方法參數來給每一個參數一個名字。不然,多參數將會以它們的順序位置來被命名。好比

#{1},#{2} 等,這是默認的。

使用@Param(「person」),SQL中參數應該被命名爲#{person}。

 

 

 注意注意:

使用駝峯法密碼命名屬性變量,並開啓mybatis的駝峯命名法,會將數據表字段的下劃線"_"和他下一個臨近的字母轉成大寫:

pojo:

userId

數據表字段:

user_id

相關文章
相關標籤/搜索