本文主要是介绍Mybatis——鉴别器映射,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
鉴别器映射
有时一个单独的数据库查询会返回很多种不同数据类型的结果集。
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();}
}
这篇关于Mybatis——鉴别器映射的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!