鉴别器映射
有时一个单独的数据库查询会返回很多种不同数据类型的结果集。
discriminator鉴别器元素可以用来处理这种情况
数据库表结构
创建实体类、映射接口和映射文件
实体类employee
package org.example.demo2;
import lombok.Data;
@Data
public class Employee {
private Integer employeeId;
private String employeeName;
}
实体类HourlyEmployee
package org.example.demo2;
import lombok.Data;
@Data
public class HourlyEmployee extends Employee{
private Double rate;
}
实体类SalaryEmployee
package org.example.demo2;
import lombok.Data;
@Data
public class SalaryEmployee extends Employee{
private Double salary;
}
EmployeeMapper
package org.example.mapper;
import org.example.demo2.Employee;
public interface EmployeeMapper {
Employee findEmployeeById(Integer employeeId);
}
EmployeeMapper.xml
使用resultMap的extends属性来映射两个子类的属性
使用discriminator元素映射employee_type字段
discriminator元素常用的两个属性如下:
column:该属性用于设置需要进行鉴别比较值的列
javaType:该属性用于指定列的类型
discriminator元素可以有1个或者多个case子元素,case元素包含三个属性
value:该值用来匹配column指定字段的值
resultMap:当value值和column的值匹配时的结果映射,优先级高于resultType
resultType:当value值和column的值匹配时的结果类型
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.example.mapper.EmployeeMapper">
<resultMap id="employeeMap" type="org.example.demo2.Employee">
<id property="employeeId" column="employee_id"/>
<result property="employeeName" column="employee_name"/>
</resultMap>
<resultMap id="hourlyMap" type="org.example.demo2.HourlyEmployee" extends="employeeMap">
<result property="rate" column="rate"/>
</resultMap>
<resultMap id="salaryMap" type="org.example.demo2.SalaryEmployee" extends="employeeMap">
<result property="salary" column="salary"/>
</resultMap>
<resultMap id="selectMap" type="org.example.demo2.Employee">
<discriminator javaType="String" column="employee_type">
<case value="HE" resultMap="hourlyMap"></case>
<case value="SE" resultMap="salaryMap"></case>
</discriminator>
</resultMap>
<select id="findEmployeeById" resultMap="selectMap">
select * from t_employee where employee_id = #{employeeId};
</select>
</mapper>
测试类
package org.example;
import org.apache.ibatis.session.SqlSession;
import org.example.demo.Order;
import org.example.demo.User;
import org.example.demo2.Employee;
import org.example.demo2.SalaryEmployee;
import org.example.mapper.EmployeeMapper;
import org.example.mapper.UserMapper;
import org.example.utils.MybatisUtil;
import java.util.List;
public class test {
public static void main(String[] args) {
test test1 = new test();
test1.selectAllEmployee();
}
public void selectAllEmployee() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
SalaryEmployee salary = (SalaryEmployee) mapper.findEmployeeById(2);
System.out.println(salary.getSalary());
sqlSession.close();
}
}