MyBatis(六) 联合查询

一、级联查询

  使用 SQL 语句将相关联的两张表对应内容查询出来,再封装到 POJO。


    <!-- 级联查询 -->
    <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>

二、分段查询

  分段查询,将查询操作分为几段步骤,比如要查询关联两张表的数据:

  1. 先通过查询条件在第一张表中获取到数据。
  2. 再带着外键去关联的表中查询。
association:
  1. 复杂对象映射
  2. POJO中的属性可能会是一个对象
  3. 我们可以使用联合查询,并以级联属性的方式封装对象。

    <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>

  当关联属性是一个集合时,在映射时需要使用到 collection 标签


    <!-- 级联查询 -->
    <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>

三、延迟加载

在全局配置文件中添加配置:


    <settings>
        ...
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"/>
        ...
    </settings>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值