Mybatis 定义集合关联查询 collection 分步延迟

文章目录

我们都知道一个部门对应多个员工,那么在以下Bean中如何查询部门下的所有员工并放入list属性中呢?

<resultMap type="com.mxthd.mybatis.bean.Department" id="Depar">
    <id column="did" property="id"/>
    <result column="dept_name" property="departmentName"/>
    <!-- collection 定义关联集合类型的属性的封装规则
    ofType:指定集合里面元素的类型
   -->
    <collection property="emps" ofType="com.mxthd.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>
<select id="getDeptByIdPlus" resultMap="Depar">
    select d.id did,d.dept_name dept_name,
    e.id eid,e.last_name last_name,e.email email,e.gender gender 
    from tab_dept d LEFT JOIN tab_empoyee e ON d.id= e.d_id where d.id=#{id}
</select>

延迟加载

collection也可以使用select

<resultMap type="com.mxthd.mybatis.bean.Department" id="MyDepa">
    <id column="id" property="id"></id>
    <result column="dept_name" property="departmentName"/>
    <collection property="emps" select="com.mxthd.mybatis.dao.EmployeeMapperPlus.getEmpByDept" column="id">
    </collection>
</resultMap>
<select id="getDeptByIdPlus" resultMap="MyDepa">
    select * from tab_dept where id=#{id}
</select>
原文链接:,转发请注明来源!

发表评论