1. 程式人生 > >mybatis-查詢(resultMap,關聯集合)-15

mybatis-查詢(resultMap,關聯集合)-15

場景:查詢部門下的所有員工

第一種方式:巢狀結果集方式
第二種方式:分步查詢方式

第一種方式:巢狀結果集方式

javaBean

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

介面

public Department getDepartmentByIdPlus(Integer id);

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>

junit

 DepartmentMapper mapper = session.getMapper(DepartmentMapper.class);
                Department dept = mapper.getDepartmentByIdPlus(2);// 分步查詢
                System.out.println(dept.toString());
                System.out.println(dept.getEmployees());
// Department{id=2, name='ceshi'}[Employee{id=1, //lastName='Jerry', email='[email protected]', gender='1'}, //Employee{id=3, lastName='Jerry', email='[email protected]', //gender='1'}]

第二種方式:分步查詢方式

public Department getDepartmentByIdStep(Integer id);
<!--public Department getDepartmentByIdStep(Integer id);-->
        <resultMap id="myDeptStep" type="com.stayreal.mybatis.Department">
            <id column="id" property="id"/>
            <result column="dept_name" property="name"/>
            <collection property="employees" select="com.stayreal.mybatis.EmployeeMapperPlus.getEmpsByDeptId"
                    column="id">
            </collection>
        </resultMap>
        <select id="getDepartmentByIdStep"  resultMap="myDeptStep">
                    select id,dept_name name from tbl_dept where id = #{id}
        </select>
 Department dept = mapper.getDepartmentByIdStep(2);// 分步查詢  collection
//Department{id=2, name='ceshi'}
//[Employee{id=1, lastName='null', email='[email protected]', gender='1'}, Employee{id=3, lastName='null', email='[email protected]', gender='1'}]