MyBatis (6) joint query

1. Cascade query

  Use SQL statements to query the corresponding content of the two associated tables, and then encapsulate them into POJOs.


    <!-- 级联查询 -->
    <resultMap type="employee" id="MyMap">
        <id column="id" property="id"/>
        <result column="last_name" property="lastName"/>
        <result column="age" property="age"/>
        <result column="dept_id" property="department.id"/>
        <result column="dept_name" property="department.departmentName"/>
    </resultMap>
    <select id="getEmpAndDepart" resultMap="MyMap">
        SELECT e.`id` id,e.`last_name` last_name,e.`age` age ,e.`email` email,
                d.`id` dept_id,d.`dept_name` dept_name 
            FROM employee e,department d WHERE e.`dept_id` = d.`id`
                AND e.id = #{id}
    </select>

Second, segment query

  Segmented query, the query operation is divided into several steps, for example, to query the data associated with two tables:

  1. First obtain the data in the first table through the query conditions.
  2. Then take the foreign key to the related table to query.

association:

  1. complex object mapping
  2. A property in a POJO may be an object
  3. We can use a union query and encapsulate the object in a way of cascading properties.

    <resultMap type="employee" id="MyMapStep">
        <id column="id" property="id"/>
        <result column="last_name" property="lastName"/>
        <result column="age" property="age"/>
        <!-- 
            对于级联属性:
                1.select :去调用指定的方法查询
                2.column :指定哪一个字段作为传入的参数
         -->
        <association property="department" 
            select="cn.edu.pzhu.cg.dao.DepartmentMapper.getDeptById"
            column="dept_id">
        </association>
    </resultMap>
    <select id="getEmpByStep" resultMap="MyMapStep">
        select * from employee where id=#{id}
    </select>

  When the associated property is a collection, the collection tag needs to be used when mapping


    <!-- 级联查询 -->
    <resultMap type="cn.edu.pzhu.cg.entities.Department" id="MyDeptStep">
        <id column="id" property="id"/>
        <result column="departmentName" property="departmentName"/>

        //映射集合属性
        //emps  为 Department 的一个集合属性
        <collection property="emps" 
            select="cn.edu.pzhu.cg.dao.EmployeeMapper.getEmps"
            column="id">
        </collection>
    </resultMap>
    <select id="getDeptAndEmpsById" resultMap="MyDeptStep">
        select id id,dept_name departmentName from department where id=#{id}
    </select>

3. Lazy Loading

Add the configuration to the global configuration file:


    <settings>
        ...
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"/>
        ...
    </settings>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324619845&siteId=291194637
Recommended