之前说了由Employee找Department,这一节讲一讲由Department找Employee,显然前者是多对一的关系,而后者是一对多的关系。
Department的JavaBean:
private Integer id; |
接口中的方法:
Department getDepByIdPlus(Integer id);
查询的SQL语句:
<select id="getDepByIdPlus" resultMap="Dep"> |
接下来编写resultMap,
collection:定义关联集合类型的属性的封装规则
ofType:指定集合里面的元素类型
<resultMap id="Dep" type="com.figsprite.bean.Department"> |
其实就是一个resultMap套着另外一个resultMap格式的collection
@Test |
collection标签的分步查询
与之前的association基本一致
- <resultMap id="DepStep" type="com.figsprite.bean.Department">
- <id property="id" column="id"/>
- <result property="departmentName" column="department_name"/>
- <collection property="employeeList"
- select="com.figsprite.dao.EmployeeMapperPlus.getDepByEmp"
- column="id">
- </collection>
- </resultMap>
11. <select id="getDepByIdStep" resultMap="DepStep">
12. select id,department_name from tb_department where id=#{id}
13. </select>
- @Test
- public void test1() throws IOException {
- SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
- SqlSession sqlOpenSession = sqlSessionFactory.openSession();
- try {
- DepartmentMapper departmentMapper = sqlOpenSession.getMapper(DepartmentMapper.class);
- Department department = departmentMapper.getDepByIdStep(1);
- System.out.println(department.getEmployeeList().get(0));
- } finally {
- sqlOpenSession.close();
- }
13. }
DEBUG [main] - ==> Preparing: select id,department_name from tb_department where id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <== Total: 1
DEBUG [main] - ==> Preparing: select * from tb_employee where d_id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <== Total: 2
日志打印出的是两条SQL语句
多值传递的分步查询
上面的例子中,无论是association还是collection在第一步SQL语句中传的都是单一值给第二条SQL语句当条件,接下来介绍第一步SQL语句传多值给SQL语句。
只要将这些多列值封装成map传递即可,
column={key1=column1,key2=column2}
- <resultMap id="DepStep" type="com.figsprite.bean.Department">
- <id property="id" column="id"/>
- <result property="departmentName" column="department_name"/>
- <collection property="employeeList"
- select="com.figsprite.dao.EmployeeMapperPlus.getDepByEmp"
- column="{did=id}">
- </collection>
- </resultMap>
注意这里column的写法。
在分步查询的时候还有一个属性fetchType,在默认情况下它的值是lazy,表示使用延迟,eager立即查询,这样即使全局设置了分步查询也不会有影响。
鉴别器discriminator
Mybatis可以使用鉴别器判断某列值,然后根据这个值做不同的封装行为。