1.鉴别器 * 查询汽车表,根据类型封装成不同的对象
创建公共交通类作为基类
package com.zixue.entity; /** * 交通工具实体类 ,封装汽车表中公用的字段 * */ public class Vehicle { private int id; private String type; private String color; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } }
package com.zixue.entity; /** * 小汽车实体类 封装小汽车相关字段 * */ public class Car extends Vehicle{ private int doorSize; public int getDoorSize() { return doorSize; } public void setDoorSize(int doorSize) { this.doorSize = doorSize; } }
package com.zixue.entity; /** * 卡车实体类,封装卡车相关的字段 * */ public class Truck extends Vehicle{ public int boxSize; public int getBoxSize() { return boxSize; } public void setBoxSize(int boxSize) { this.boxSize = boxSize; } }
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<mapper namespace="com.zixue.dao.VehicleDao">
<resultMap type="com.zixue.entity.Vehicle" id="vehicleMap">
<id property="id" column="id"/>
<result property="color" column="color"/>
<discriminator javaType="java.lang.String" column="type">
<case value="T" resultType="com.zixue.entity.Truck">
<result property="boxSize" column="boxSize"/>
</case>
<case value="C" resultType="com.zixue.entity.Car">
<result property="doorSize" column="doorSize"/>
</case>
</discriminator>
</resultMap>
<select id="findAll" resultMap="vehicleMap">
select * from t_car
</select>
</mapper>
package com.zixue.dao; import java.util.List; import com.zixue.annotation.MyBatisRepository; import com.zixue.entity.Vehicle; @MyBatisRepository public interface VehicleDao { List<Vehicle> findAll(); }
package com.zixue.test; import java.util.List; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.zixue.dao.VehicleDao; import com.zixue.entity.Vehicle; public class TestFindAll { /** * 鉴别器 * 查询汽车表,根据类型封装成不同的对象 * */ @Test public void testFindAll(){ ApplicationContext ac =new ClassPathXmlApplicationContext("applicationContext.xml"); VehicleDao dao =ac.getBean(VehicleDao.class); List<Vehicle> list =dao.findAll(); for( Vehicle v:list){ System.out.println(v); } } }
原文:https://www.cnblogs.com/erbinok/p/9092109.html