這篇文章就來討論一下怎樣利用mybatis實現繼承映射。
類圖
有一個機動車父類,它有兩個子類:Car和Bus
關系模型(t_vehicle)
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>標簽中的內容,依據鑒別字段的值自己主動映射成相應的子類
client測試代碼
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());
非常easy的一個樣例,和大家分享一下
