Mybatis: one-to-many mapping processing



foreword

This blogger will use CSDN to record his personal income and learning on the way to study software development. Interested friends can pay attention to the blogger! Perhaps a person can go fast alone, but a group of people can go farther!

I. Overview

A one-to-many relationship means that one entity object (one) can have multiple associated objects (many).
For example, a user can have multiple orders, or a department can have multiple employees.

In databases, one-to-many relationships are usually implemented through foreign keys.

2. Create a data model

Define the entity class: define the main table entity class and the secondary table entity class. The main table entity class contains the List collection attribute of the secondary table entity class .

Now we use this to create the object data model of an object-oriented language:

Dept.java

public class Dept {
    
    
    private Integer did;
    private String deptName;
    private List<Emp> emps;//用于表示数据库一对多的关系
    // 省略构造函数和getter/setter方法
}

Emp.java

public class Emp {
    
    
    private Integer eid;
    private String empName;
    private Integer age;
    private String sex;
    private String email;
    // 省略构造函数和getter/setter方法
}

Three, the problem

Suppose we now have two tables, one employee table and one department table, now we want to get the department and all the employee information in the department

4. Solutions

1. Solution 1: collection (nested result)

Nested result: By using the nested result method, you can nest the properties of the associated entity object into the properties of the main entity object through nesting while querying the main entity object. The implementation of this method needs to Mapper.xmldefine a SQL statement in the file, and map the attributes of the associated entity object to the attributes of the main entity object in a nested manner. When defining the mapping relationship, you need to use resultMaptags to define the mapping relationship between the main entity object and the associated entity object, and use collectionthe tag to nest the attributes of the associated entity object.

DeptMapper.java

 /**
     * @description:获取部门以及部门中所有的员工信息
     * @author: Hey
     * @date: 2022/7/4 10:46
     * @param: [did]
     * @return: com.ir.mybatis.pojo.Dept
     **/
    Dept getDeptAndEmp(@Param("did") Integer did);

DeptMapper.xml

	<resultMap id="deptAndEmpResultMap" type="Dept">
        <id property="did" column="did"></id>
        <result property="deptName" column="dept_name"></result>
        <!--
            collection:处理一对多的映射关系
            ofType:表示该属性所对应的集合中存储数据的类型
        -->
        <collection property="emps" ofType="Emp">
            <id property="eid" column="eid"></id>
            <result property="empName" column="emp_name"></result>
            <result property="age" column="age"></result>
            <result property="sex" column="sex"></result>
            <result property="email" column="email"></result>
        </collection>
    </resultMap>
    <!--Dept getDeptAndEmp(@Param("did") Integer did);-->
    <select id="getDeptAndEmp" resultMap="deptAndEmpResultMap">
        select * from t_dept left join t_emp on t_dept.did = t_emp.did where t_dept.did = #{did}
    </select>

ResultTest.java

 /**
     * @description:获取部门以及部门中所有的员工信息
     * @author: Hey
     * @date: 2022/7/4 10:54
     * @param: []
     * @return: void
     **/
    @Test
    public void testGetDeptAndEmp(){
    
    
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        DeptMapper mapper = sqlSession.getMapper(DeptMapper.class);
        Dept dept = mapper.getDeptAndEmp(1);
        System.out.println(dept);
        /**
         * Dept{
         * did=1, deptName='A',
         * emps=[
         * Emp{eid=1, empName='喜羊羊', age=34, sex='男', email='[email protected]'},
         * Emp{eid=4, empName='沸羊羊', age=23, sex='男', email='[email protected]'}
         * ]
         * }
         */
    }

2. Solution 2: step-by-step query (nested query)

Nested query: By using the nested query method, while querying the main entity object, multiple associated entity objects can be obtained by querying associated entity objects. The implementation of this method needs Mapper.xmlto define two independent SQL statements in the file, one is used to query the main entity object, and the other is used to query the associated entity object. When querying the main entity object, selectthe query of the associated entity object is performed by using the sub-label of the label, and the query result is mapped to the attribute of the main entity object.

DeptMapper

 /**
     * @description:通过分步查询查询部门以及部门中所有的员工信息
     *              分步查询第一步:查询部门信息
     * @author: Hey
     * @date: 2022/7/4 12:31
     * @param: [did]
     * @return: com.ir.mybatis.pojo.Dept
     **/
    Dept getDeptAndEmpByStepOne(@Param("did") Integer did);

DeptMapper.xml

 <resultMap id="deptAndEmpByStepResultMap" type="Dept">
        <id property="did" column="did"></id>
        <result property="deptName" column="dept_name"></result>
        <collection property="emps"
                    select="com.ir.mybatis.mapper.EmpMapper.getDeptAndEmpByStepTwo"
                    column="did" fetchType="eager">

        </collection>
    </resultMap>
    
    <select id="getDeptAndEmpByStepOne" resultType="deptAndEmpByStepResultMap">
        select * from t_dept where did = #{did}
    </select>

EmpMapper

/**
     * @description:通过分步查询查询部门以及部门中所有的员工信息
     *              分步查询第二步:根据did查询员工信息
     * @author: Hey
     * @date: 2022/7/4 12:36
     * @param: [did]
     * @return: java.util.List<com.ir.mybatis.pojo.Emp>
     **/
    List<Emp> getDeptAndEmpByStepTwo(@Param("did") Integer did);

EmpMapper.xml

<select id="getDeptAndEmpByStepTwo"  resultType="Emp">
      select * from t_emp where did = #{
    
    did}
    </select>

ResultTest

/**
     * @description:通过分步查询查询部门以及部门中所有的员工信息
     * @author: Hey
     * @date: 2022/7/4 12:40
     * @param: []
     * @return: void
     **/
    @Test
    public void testGetDeptAndEmpByStep(){
    
    
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        DeptMapper mapper = sqlSession.getMapper(DeptMapper.class);
        Dept dept = mapper.getDeptAndEmpByStepOne(1);
        System.out.println(dept.getDeptName());
    }

Whether you use nested query or nested result, you need to define the corresponding SQL statement and mapping relationship in the Mapper.xml file. At the same time, in order to improve query performance, you can use Mybatis's lazy loading mechanism to reduce the number of queries and improve data access efficiency.

Guess you like

Origin blog.csdn.net/weixin_52533007/article/details/131988933