mybatis实现继承映射

时间:2023-01-26 05:13:18

ORM 框架的优势在于能让我们利用面向对象的思维去操作数据库, hibernate 作为重量级的 ORM 框架对面向对象的支持很强大。作为半自动化的 mybatis ,对面向对象的支持也是很完备的。这篇文章就来讨论一下如何利用 mybatis

实现继承映射。

类图

mybatis实现继承映射

有一个机动车父类,它有两个子类: Car 和 Bus

关系模型 (t_vehicle)

mybatis实现继承映射

ORM 映射有一个原则:对象模型细粒度,关系模型粗粒度。所以我们将所有的车都存储一张表里( t_vehicle ),通过鉴别字段 vType 来区分车的类型( "c" 代表 Car ,"b" 代表 Bus )

三个实体类的代码

Vehicle

package com.tgb.mybatis.model;

public class Vehicle {
//主键id
private String id;
//车的名字
private String name; public String getId() {
return id;
} public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} }

Car

package com.tgb.mybatis.model;

public class Car extends Vehicle {
//车门的数量
private int carDoor;
//车的牌子
private String band; public int getCarDoor() {
return carDoor;
}
public void setCarDoor(int carDoor) {
this.carDoor = carDoor;
}
public String getBand() {
return band;
}
public void setBand(String band) {
this.band = band;
} }

Bus

package com.tgb.mybatis.model;

public class Bus extends Vehicle {
//公共汽车的容量
private int capacity; public int getCapacity() {
return capacity;
} public void setCapacity(int capacity) {
this.capacity = capacity;
} }

看看对“车”进行操作的 Mapper 接口【只关注查询】

package com.tgb.mybatis.data;

import com.tgb.mybatis.model.Bus;
import com.tgb.mybatis.model.Car;
import com.tgb.mybatis.model.Vehicle; public interface VehicleMapper {
//根据id查询机动车
Vehicle getVechicleById(String id);
//根据名字查询小汽车
Car getCarByName(String name);
}

xml 方式 ORM 映射

<?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="com.tgb.mybatis.data.VehicleMapper">
<select id="getVechicleById" resultMap="vehicleMap">
SELECT * FROM TB_VEHICLE WHERE VID = #{id}
</select>
<select id="getCarByName" resultMap="vehicleMap">
SELECT * FROM TB_VEHICLE WHERE VTYPE='c' AND VName = #{id}
</select>
<resultMap type="vehicle" id="vehicleMap">
<id property="id" column="vId"/>
<result property="name" column="vName"/>
<discriminator javaType="string" column="vType">
<case value="c" resultType="car">
<result property="carDoor" column="cardoor"/>
<result property="band" column="band"/>
</case>
<case value="b" resultType="bus">
<result property="capacity" column="capacity"/>
</case>
</discriminator>
</resultMap>
</mapper>

分析

其中最为关键的就是<discriminator > 标签中的内容,根据鉴别字段的值自动映射成对应的子类

客户端测试代码

VehicleMapper mapper = session.getMapper(VehicleMapper.class);
Vehicle vehicle = mapper.getVechicleById("1");
System.out.println(vehicle.getName());
Car car = mapper.getCarByName("路虎007");
System.out.println(car.getBand());