1. 程式人生 > >MyBatis映射文件6

MyBatis映射文件6

定義 rtm sprite temp 說了 規則 接下來 () tor

之前說了由Employee找Department,這一節講一講由Department找Employee,顯然前者是多對一的關系,而後者是一對多的關系。

Department的JavaBean:

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

接口中的方法:

Department getDepByIdPlus(Integer id);

查詢的SQL語句:

<select id="getDepByIdPlus" resultMap="Dep">


SELECT d.`id` did,d.`department_name` dep_name,e.`id` eid,e.`last_name` last_name,e.`email` email,e.`gender` gender
FROM tb_department d LEFT JOIN tb_employee e
ON d.`id`=e.`d_id`
WHERE d.`id`=2;
</select>

接下來編寫resultMap,

collection:定義關聯集合類型的屬性的封裝規則

ofType:指定集合裏面的元素類型

<resultMap id=

"Dep" type="com.figsprite.bean.Department">
<id property="id" column="did"/>
<result property="departmentName" column="dep_name"/>
<collection property="employeeList" ofType="com.figsprite.bean.Employee">
<id property="id" column="eid"/>

<result property="lastName" column="last_name"/>
<result property="gender" column="gender"/>
<result property="email" column="email"/>
</collection>
</resultMap>

其實就是一個resultMap套著另外一個resultMap格式的collection

@Test
public void test2() throws IOException {

SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession sqlOpenSession = sqlSessionFactory.openSession();
try {
DepartmentMapper departmentMapper = sqlOpenSession.getMapper(DepartmentMapper.class);
Department department = departmentMapper.getDepByIdPlus(1);
for (Employee e : department.getEmployeeList()) {
System.out.println(e);
}
} finally {
sqlOpenSession.close();
}
}

MyBatis映射文件6