MyBatis-- annotation style development

MyBatis-- annotation style development

MyBatis annotations, mainly used to replace the mapping file. The map file is nothing more than kept the CRUD sql mapping of the label. So, MyBatis annotations, is to replace sql tag mapping file.

Common explanatory notes:

annotation Explanation
@Insert Implement new
@Update Update achieve
@Delete Delete achieve
@Select Implement the query
@Result Package achieve the results set
@Results It can be used with @Result, packaging a plurality of result sets
@ResultMap To achieve encapsulation defined reference @Results
@One Achieve the result set one-package
@Many Package-many result set
@SelectProvider Dynamic SQL mapping
@CacheNamespace Achieved using annotations secondary cache

First, the basic CRUD

1.@Insert

Its value attribute is used to specify the insert statements to be executed.

2.@SelectKey

Xml for replacing the <selectKey/>label, returns the id value for the newly inserted data.

@SelectKey(statement="select @@identity",resultType=int.class,keyProperty="id",before=false
复制代码
  • statement: get the primary key of the newly inserted record worth sql statement
  • keyProperty: that property acquired after the primary key returns the object initialization
  • resultType: Return Value Type
  • before: generating a primary key designated with respect to the sequence of the insert statement executed, the attribute can be omitted

3.@Delete

Its value attribute is used to specify the delete statement to be executed.

4.@Update

Its value attribute is used to specify the update statement to be executed.

5.@Select

Its value attribute is used to specify the select statement to be executed.

Programming example:

SqlMapConfig.xml:

<?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="jdbcConfig.properties"></properties>
    <!--配置别名-->
    <typeAliases>
        <package name="com.hcx.domain"></package>
    </typeAliases>
    <!-- 配置环境-->
    <environments default="mysql">
        <environment id="mysql">
            <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>
    <!-- 指定带有注解的dao接口所在位置 -->
    <mappers>
        <mapper class="com.hcx.dao.StudentDao"></mapper>
    </mappers>
</configuration>
复制代码

1. Modify dao interfaces:

public interface IStudentDao {
	@Insert(value={"insert into student(name,age,score) values(#{name},#{age},#{score})"})
	void insertStudent(Student student);	
	
	@Insert("insert into student(name,age,score) values(#{name},#{age},#{score})")
	@SelectKey(statement="select @@identity",resultType=int.class,keyProperty="id",before=false)
	void insertStudentCacheId(Student student);
	
	@Delete(value="delete from student where id=#{id}")
	void deleteStudentById(int id);
	
	@Update("update student set name=#{name},age=#{age},score=#{score} where id=#{id}")
	void updateStudent(Student student);
	
	@Select("select * from student")
	List<Student> selectAllStudents();
	
	@Select("select * from student where id=#{id}")
	Student selectStudentById(int id);
	
	@Select("select * from student where name like '%' #{name} '%'")
	List<Student> selectStudentsByName(String name);
	
}
复制代码

2. Delete map file

3. Modify the main configuration file

In the absence of a mapping file, so you can not use the main configuration file <mapper/>location of the registered mapper. Require the use of <package/>labels

<!-- 注册映射文件 -->
<mappers>  
    <package name="com.hcx.dao"/>  
</mappers>
复制代码

Note: After using annotations, regardless of the main configuration file (SqlMapConfig.xml) Is there a reference map file, mapping file can not exist. You can delete or placed under another directory.

Second, the realization of complex relational mapping

1. @ Result When a database is inconsistent physical properties and field names, use @Resultannotations claim mapping relationship

@Results(id = "studentMap",value={
            @Result(id=true,column = "id",property = "studentId"),
            @Result(column = "name",property = "studentName"),
            @Result(column = "age",property = "studentAge"),
            @Result(column = "score",property = "studentScore"),
    })
复制代码

id: Uniquely identifies this map, can then be referenced directly, without having to repeat writing id=true: identified as a primary key field column: database field names property: the entity attribute name

2. @ ResultMap references defined ResultMap

Student:

@Data
@ToString
public class Student implements Serializable{
    private Integer studentId;
    private String studentName;
    private int studentAge;
    private double studentScore;
}
复制代码

StudentDao:

public interface StudentDao {

    @Select("select * from student")
    @Results(id = "studentMap",value={
            @Result(id=true,column = "id",property = "studentId"),
            @Result(column = "name",property = "studentName"),
            @Result(column = "age",property = "studentAge"),
            @Result(column = "score",property = "studentScore"),
    })
    List<Student> findAll();

    @Select("select * from student where id=#{id}")
    @ResultMap(value = {"studentMap"})
    Student findById(Integer id);


    @Select("select * from student where name like #{name}")
    @ResultMap(value = {"studentMap"})
    List<Student> findStudentByName(String name);

}
复制代码

AnnotationCrudTest:

public class AnnotationCrudTest {

    private InputStream in;
    private SqlSessionFactory factory;
    private SqlSession session;
    private StudentDao studentDao;

    @Before
    public  void init()throws Exception{
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        factory = new SqlSessionFactoryBuilder().build(in);
        session = factory.openSession();
        studentDao = session.getMapper(StudentDao.class);
    }

    @After
    public  void destroy()throws  Exception{
        session.commit();
        session.close();
        in.close();
    }

    @Test
    public void testFindAll(){
        List<Student> students = studentDao.findAll();
        for(Student student : students){
            System.out.println(student);
        }
    }


    @Test
    public void testFindById(){
        Student student = studentDao.findById(1);
        System.out.println(student);
    }


    @Test
    public  void testFindByName(){
        List<Student> students = studentDao.findStudentByName("%小红%");
        for(Student student : students){
            System.out.println(student);
        }
    }
}
复制代码

Third, to achieve complex multi-table queries

1. One to One

Account:

@Data
@ToString
public class Account {
    private Integer id;
    private Integer studentId;
    private Double money;

    //多对一:一个账户只能属于一个学生
    private Student student;
}
复制代码

AccountDao:

public interface AccountDao {
    /**
     * 查询所有账户并获取每个账户所属用户信息
     * @return
     */
    @Select("select * from account")
    @Results(id = "accountMap",value = {
            @Result(id = true,column = "id",property = "id"),
            @Result(column = "studentId",property = "studentId"),
            @Result(column = "money",property = "money"),
            @Result(property = "student",column = "studentId",one = @One(select = "com.hcx.dao.StudentDao.findById",
                    fetchType = FetchType.EAGER))
    })
    List<Account> findAll();
}
复制代码

StudentDao:

public interface StudentDao {

    @Select("select * from student")
    @Results(id = "studentMap",value={
            @Result(id=true,column = "id",property = "studentId"),
            @Result(column = "name",property = "studentName"),
            @Result(column = "age",property = "studentAge"),
            @Result(column = "score",property = "studentScore"),
    })
    List<Student> findAll();

    @Select("select * from student where id=#{id}")
    @ResultMap(value = {"studentMap"})
    Student findById(Integer id);


    @Select("select * from student where name like #{name}")
    @ResultMap(value = {"studentMap"})
    List<Student> findStudentByName(String name);
}
复制代码

AccountTest:

    @Test
    public void testFindAll(){
        List<Account> accounts = accountDao.findAll();
        for(Account account : accounts){
            System.out.println(account);
//            System.out.println(account.getStudent());
        }
    }
复制代码

Note: usually a choice to load immediately, the multi-selection delay loading

2. many

Student:

@Data
@ToString
public class Student implements Serializable{
    private Integer studentId;
    private String studentName;
    private int studentAge;
    private double studentScore;
    //一对多,一个用户对应多个账户
    private List<Account> accounts;
}
复制代码

StudentDao:

public interface StudentDao {

    @Select("select * from student")
    @Results(id = "studentMap",value={
            @Result(id=true,column = "id",property = "studentId"),
            @Result(column = "name",property = "studentName"),
            @Result(column = "age",property = "studentAge"),
            @Result(column = "score",property = "studentScore"),
            @Result(property = "accounts",column = "id",
                    many = @Many(select = "com.hcx.dao.AccountDao.findAccountByStudentId",fetchType = FetchType.LAZY))
    })
    List<Student> findAll();

    @Select("select * from student where id=#{id}")
    @ResultMap(value = {"studentMap"})
    Student findById(Integer id);

    @Select("select * from student where name like #{name}")
    @ResultMap(value = {"studentMap"})
    List<Student> findStudentByName(String name);

}
复制代码

AccountDao:

public interface AccountDao {

    /**
     * 查询所有账户并获取每个账户所属用户信息
     * @return
     */
    @Select("select * from account")
    @Results(id = "accountMap",value = {
            @Result(id = true,column = "id",property = "id"),
            @Result(column = "studentId",property = "studentId"),
            @Result(column = "money",property = "money"),
            @Result(property = "student",column = "studentId",one = @One(select = "com.hcx.dao.StudentDao.findById",
                    fetchType = FetchType.EAGER))
    })
    List<Account> findAll();

    /**
     * 根据学生id查询学生信息
     * @param studentId
     * @return
     */
    @Select("select * from account where studentId=#{studentId}")
    List<Account> findAccountByStudentId(Integer studentId);
}
复制代码

Test:

    @Test
    public void testFindAll(){
        List<Student> students = studentDao.findAll();
        for(Student student : students){
            System.out.println(student);
        }
    }

复制代码

Attaining the secondary cache

Cache: Default to open:

    @Test
    public void testFindById(){
        Student student = studentDao.findById(1);
        System.out.println(student);

        Student student1 = studentDao.findById(1);
        System.out.println(student1);

        //true
        System.out.println(student==student1);
    }
复制代码

Open secondary cache in the main configuration file (on by default, the configuration may not) sqlMapConfig.xml:

<?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="jdbcConfig.properties"></properties>
    <!--设置开启二级缓存-->
    <settings>
        <setting name="cacheEnabled" value="true"/>
    </settings>

    <!--配置别名-->
    <typeAliases>
        <package name="com.hcx.domain"></package>
    </typeAliases>
    <!-- 配置环境-->
    <environments default="mysql">
        <environment id="mysql">
            <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>
    <!-- 指定带有注解的dao接口所在位置 -->
    <mappers>
        <!--<mapper class="com.hcx.dao.StudentDao"></mapper>-->
        <package name="com.hcx.dao"></package>
    </mappers>
</configuration>
复制代码

Use annotations on the mapper@CacheNamespace(blocking=true)

@CacheNamespace(blocking = true)
public interface StudentDao {

    @Select("select * from student")
    @Results(id = "studentMap",value={
            @Result(id=true,column = "id",property = "studentId"),
            @Result(column = "name",property = "studentName"),
            @Result(column = "age",property = "studentAge"),
            @Result(column = "score",property = "studentScore"),
            @Result(property = "accounts",column = "id",
                    many = @Many(select = "com.hcx.dao.AccountDao.findAccountByStudentId",fetchType = FetchType.LAZY))
    })
    List<Student> findAll();

    @Select("select * from student where id=#{id}")
    @ResultMap(value = {"studentMap"})
    Student findById(Integer id);


    @Select("select * from student where name like #{name}")
    @ResultMap(value = {"studentMap"})
    List<Student> findStudentByName(String name);

}
复制代码

Test:

@Test
    public void testFindOne(){
        SqlSession sqlSession = factory.openSession();
        StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
        Student student = studentDao.findById(1);
        System.out.println(student);
        sqlSession.close();

        SqlSession sqlSession1 = factory.openSession();
        StudentDao studentDao1 = sqlSession1.getMapper(StudentDao.class);

        Student student1 = studentDao1.findById(1);
        System.out.println(student1);

        sqlSession1.close();
        //false
        System.out.println(student==student1);
    }
复制代码

Guess you like

Origin juejin.im/post/5dee427af265da33d7441e3d