鉴别器
<discriminator javaType=""></discriminator>
鉴别器:mybatis可以使用discriminator判断某列的值,然后根据某列的值改变封装行为。
例如:封装Employee:
如果查出的是女生:就把部门信息查询出来,否则不查询;
如果是男生,把last_name这一列的值赋值给email;
- 在dao接口创建对应的查询方法
public interface EmployeeMapper {
public Employee testDiscriminator(Integer id);
}
- 通过鉴别器实现改变封装行为。
<resultMap id="MyDiscri" type="com.fzl.mybatis.bean.Employee">
<id column="id" property="id"/>
<result column="last_name" property="lastName"/>
<result column="gender" property="gender"/>
<result column="email" property="email"/>
<!--如果是女性,则查询其部门信息,如果是男性,则不查部门信息,将gender的值赋给last_name,last_name赋值给gender -->
<discriminator javaType="string" column="gender">
<!-- 如果是女性 ,resultType:指定封装的结果类型;不能缺少。-->
<case value="0" resultType="com.fzl.mybatis.bean.Employee">
<association property="dept" select="com.fzl.mybatis.dao.DepartmentMapper.getDeptById" column="d_id"></association>
</case>
<!--如果是男性,把last_name这一列的值赋值给email; -->
<case value="1" resultType="com.fzl.mybatis.bean.Employee">
<id column="id" property="id"/>
<result column="last_name" property="lastName"/>
<result column="gender" property="gender"/>
<result column="last_ame" property="email"/>
</case>
</discriminator>
</resultMap>
<select id="testDiscriminator" resultMap="MyDiscri">
select * from tbl_employee where id=#{id}
</select>
- 测试
@Test
public void test5() throws IOException {
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession();
try{
EmployeeMapper employeeMapper = openSession.getMapper(EmployeeMapper.class);
Employee employee = employeeMapper.testDiscriminator(1);
System.out.println(employee.getLastName());
System.out.println(employee);
}finally{
openSession.close();
}
}
- 测试结果
(1)女生
(2)男生