mybatis嵌套查询

需求:

list中有个字段为list的情况;

解决办法:

使用mybatis的嵌套查询功能;

实例:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.mybatis.dao.DepartmentMapper">
 
    <!-- collection嵌套结果集的方式,定义关联的集合类型元素的封装规则-->
    
    <!-- 嵌套结果集的方式,使用collection标签定义关联的集合类型的属性封装规则 -->
    <resultMap type="com.atguigu.mybatis.bean.Department" id="MyDept">
        <id column="did" property="id"/>
        <result column="dept_name" property="departmentName"/>
        <!-- 
        collection定义关联结合类型的属性的封装规则
        ofType:指定集合里面元素的类型
        -->
        <collection property="emps" ofType="com.atguigu.mybatis.bean.Employee">
            <!-- 定义这个集合中元素的封装规则 -->
            <id column="eid" property="id"/>
            <result column="last_name" property="lastName"/>
            <result column="email" property="email"/>
            <result column="gender" property="gender"/>
        </collection>
    
    </resultMap>
    
    <!-- public Department getDeptByIdPlus(Integer id); -->
    <select id="getDeptByIdPlus" resultMap="MyDept" >
        SELECT
            d.id did,
            d.dept_name dept_name,
            e.id,
            e.last_name last_name,
            e.email email,
            e.gender gender
        FROM
            tbl_dept d
        LEFT JOIN tbl_employee e ON d.id = e.d_id
        WHERE
            d.id = #{id}
    </select>
    
</mapper>
1,查询语句的结果集志向定的的resultMap

2,外层resultMap中的result与定义的javabean属性值一致

3,在resultMap中添加<collect>,并指向新定义的javabean

4,在外层指向的javabean中定义内层javabean的List

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值