1. 程式人生 > >mybatis巢狀查詢物件下子物件的list

mybatis巢狀查詢物件下子物件的list

有的時候我們在查詢的時候會需要再一個物件裡返回他的子物件裡的一個list

場景:查詢某個公司下,銷售部和商務部下所有的人員

那麼我們希望返回的資料結構是:

在mybatis裡我們使用下面的方式,用一條sql語句查詢出來

巢狀結果集方式

javaBean

public class Department {
    private Integer id;
    private String name;
    private List<Employee> employees;}

介面

public Department getDepartmentByIdPlus(Integer id);
  • 1

sql對映檔案

    <!--
         private Integer id;
        private String name;
        private List<Employee> employees;
        -->
        <!-- 巢狀結果集的方式-->
        <!--public Department getDepartmentByIdPlus(Integer id);-->
        <resultMap id="myDept" type="com.stayreal.mybatis.Department">
            <id column="did" property="id"/>
            <result column="dept_name" property="name"/>
            <!-- collection定義關聯集合型別的屬性封裝規則
            offType:指定集合中的元素型別
            -->
            <collection property="employees" ofType="com.stayreal.mybatis.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="getDepartmentByIdPlus"  resultMap="myDept">
            select d.id did,d.dept_name dept_name,e.id eid,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>