使用collection查詢集合屬性


介紹resultMap中使用collection查詢集合屬性

業務需求,查詢部門中的多個人員

public class Department {

private Integer id;
private String departmentName;
private List<Employee> emps;

setter和getter省略

}

public class Employee {

private Integer id;
private String lastName;
private String email;
private String gender;
private Department dept;

setter和getter省略

}

1。在department接口寫方法

public Department getDeptByIdPlus(Integer id);

2.找到映射文件寫

<!--嵌套結果集的方式,使用collection標簽定義關聯的集合類型的屬性封裝規則 -->
<resultMap type="com.atguigu.mybatis.bean.Department" id="MyDept">
<id column="did" property="id"/>
<result column="dname" 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.dname dname,
e.id eid,e.last_name last_name,e.email email,e.gender gender
FROM department d
LEFT JOIN tbl_employee e
ON d.id=e.did
WHERE d.id=#{id}
</select>

3進行測試

@Test
public void test06() throws IOException{
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession();

try{
DepartmentMapper mapper = openSession.getMapper(DepartmentMapper.class);
Department department = mapper.getDeptByIdPlus(1);
System.out.println(department);
System.out.println(department.getEmps());

}finally{
openSession.close();
}
}

}

運行結果如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM