MyBatis annotation development --- realize custom mapping relationship and associated query

Table of contents

1. Use annotations to implement custom mapping relationships

1. Write annotation method

2. Write the test method

3. View the running results

2. Use annotations to realize one-to-one association query

1. Write annotation method

2. Write the test method

3. View the running results

3. Use annotations to realize one-to-many association query

1. Write annotation method

2. Write the test method

3. View the running results

4. Comparison of development of annotation files and mapping files


1. Use annotations to implement custom mapping relationships

        When the POJO attribute name is inconsistent with the database column name, you need to customize the mapping relationship between the entity class and the result set. In MyBatis annotation development, use @Results to define and use custom mapping, and use @ResultMap to use custom mapping. The usage is as follows:

        Foreplay: In order to experience this effect, we can modify the User entity class code as follows

package com.example.pojo;

import java.io.Serializable;

public class User implements Serializable {
    private int id;
    private String username1;
    private String sex1;
    private String address1;

    public User(String programmer, String man, String shangHai) {
        this.username1 = programmer;
        this.sex1 = man;
        this.address1 = shangHai;
    }

    public User(int i, String programmer_1, String woman, String shenzhen) {
        this.id = i;
        this.username1 = programmer_1;
        this.sex1 = woman;
        this.address1 = shenzhen;
    }

    public User() {

    }
 
    public int getId() {
        return id;
    }

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

    public String getUsername1() {
        return username1;
    }

    public void setUsername1(String username1) {
        this.username1 = username1;
    }

    public String getSex1() {
        return sex1;
    }

    public void setSex1(String sex1) {
        this.sex1 = sex1;
    }

    public String getAddress1() {
        return address1;
    }

    public void setAddress1(String address1) {
        this.address1 = address1;
    }

    @Override
    public String toString() {
        return "User[ " +
                "id=" + id +
                ", username1='" + username1 + '\'' +
                ", sex1='" + sex1 + '\'' +
                ", address1='" + address1 + '\'' +
                " ]";
    }
}

1. Write annotation method

    // 查询所有用户
    @Results(id="userDiyMapper",value = {
            @Result(id = true,property = "id",column = "id"),
            @Result(property = "username1",column = "username"),
            @Result(property = "sex1",column = "sex"),
            @Result(property = "address1",column = "address")
    })
    @Select("select * from user")
    List<User> findAll1();

    // 根据id查询
    @ResultMap("userDiyMapper")
    @Select("select * from user where id = #{id}")
    User findById(int id);

Note: here property corresponds to the attribute name of the entity class, and column corresponds to the column name of the database table 

2. Write the test method

    @Test
    public void testFindAll1(){
        List<User> all = userMapper.findAll1();
        all.forEach(System.out::println);
        System.out.println("---------------------");
        System.out.println(userMapper.findById(5));
    }

        See if you can query all users and users with id 5, and pay attention to the corresponding attribute names 

3. View the running results

        OK, it seems to be in line with our expectations. 

2. Use annotations to realize one-to-one association query

        In the annotation development of MyBatis, only decomposed queries are supported for multi-table queries, and join queries are not supported.

        Here we use the student table and the class table for comparison, so we first create the Student entity class and the Classes entity class

ClassesEntity class 

package com.example.pojo;

import java.util.List;

public class Classes {
    private int cid;
    private String className;
    private List<Student> studentList;

    public int getCid() {
        return cid;
    }

    public void setCid(int cid) {
        this.cid = cid;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    public List<Student> getStudentList() {
        return studentList;
    }

    public void setStudentList(List<Student> studentList) {
        this.studentList = studentList;
    }

    @Override
    public String toString() {
        return "Classes[ " +
                "cid=" + cid +
                ", className='" + className + '\'' +
                ", studentList=" + studentList + 
                " ]";
    }
}

Student entity class

package com.example.pojo;

public class Student {
    private int sid;
    private String name;
    private int age;
    private String sex;
    private Classes classes;

    public int getSid() {
        return sid;
    }

    public void setSid(int sid) {
        this.sid = sid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

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

    public Classes getClasses() {
        return classes;
    }

    public void setClasses(Classes classes) {
        this.classes = classes;
    }

    @Override
    public String toString() {
        return "Student[ " +
                "sid=" + sid +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                ", classes=" + classes +
                " ]";
    }
}

1. Write annotation method

StudentMapper adds query for all users

package com.example.mapper;

import com.example.pojo.Student;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

public interface StudentMapper {
    @Select("select * from student")
    // 自定义映射关系
    @Results(id = "studentMapper",value = {
            @Result(id = true,property = "sid",column = "sid"),
            @Result(property = "name",column = "name"),
            @Result(property = "age",column = "age"),
            @Result(property = "sex",column = "sex"),
            /**
             * property:属性名
             * column:调用从表方法时传入的参数列
             * one:表示该属性是一个对象
             * select:调用的是从表方法
             * fetchType:加载方式
             */
            @Result(property = "classes",column = "classId",
                one = @One(select = "com.example.mapper.ClassesMapper.findByCid",
                        fetchType = FetchType.EAGER)
                )
    })
    List<Student> findAll();
}

ClassesMapper adds query class based on id

package com.example.mapper;

import com.example.pojo.Classes;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

public interface ClassesMapper {
    // 根据id查询班级
    @Select("select * from classes where cid = #{cid}")
    Classes findByCid(Integer id);
}

2. Write the test method

// 测试一对一查询
    @Test
    public void testFindAllStudent(){
        StudentMapper studentMapper = session.getMapper(StudentMapper.class);
        List<Student> all = studentMapper.findAll();
        all.forEach(System.out::println);
    }

        See if you can query the class corresponding to the student, if you can, the query is successful 

3. View the running results

        OK, looking at the picture, we have successfully queried the class corresponding to each student 

3. Use annotations to realize one-to-many association query

        Here we mainly realize that when querying all classes, the corresponding student list is also queried.

1. Write annotation method

Add StudentMapper to query students based on class id

// 根据班级Id查询学生
    @Select("select * from student where ClassId = #{classId}")
    List<Student> findByClassId(int classId);

Classes add query for all classes

// 查询所有班级
    @Select("select * from classes")
    @Results(id = "classMapper",value = {
            @Result(id = true,property = "cid",column = "cid"),
            @Result(property = "className",column = "className"),
            // many:表示该属性是一个集合
            @Result(property = "studentList",column = "cid",
            many = @Many(select = "com.example.mapper.StudentMapper.findByClassId",
                        fetchType = FetchType.LAZY))
    })
    List<Classes> findAll();

2. Write the test method

// 测试一对多查询
    @Test
    public void findAllClasses(){
        ClassesMapper classesMapper = session.getMapper(ClassesMapper.class);
        List<Classes> all = classesMapper.findAll();
        all.forEach(System.out::println);
    }

        Observe whether you can find out the list of students corresponding to the class

3. View the running results

OK, it is indeed possible to check it out. 

4. Comparison of development of annotation files and mapping files

Annotation development is faster and mapping files are more convenient.

It is recommended to use mapping files for development in MyBatis , and annotations are recommended for Spring and SpringBoot . The specific use depends on the project situation. Their advantages are compared as follows:

Mapping file:

  • The code is decoupled from the Sql statement. When modifying, only the configuration file needs to be modified, and the source code does not need to be modified.
  • Concentrated Sql statements are conducive to quick understanding and maintenance of projects.
  • Cascading query supports both connection query and decomposed query, and annotation development only supports decomposed query.

annotation:

  • Simple configuration and high development efficiency.
  • Type safety, verification can be performed at compile time, and there is no need to wait until runtime to find errors.

Personally, I also prefer the development of mapping files, mainly for the convenience of maintenance and understanding.

Guess you like

Origin blog.csdn.net/qq_53317005/article/details/129649043