<resultMap>中关于<association>的继承细节

为了方便演示这个细节,我们首先创建一些 model:

// 轮子
public class Wheel {
	...
}
// 汽车的轮子
public class CarWheel extends Wheel {
	// 汽车的轮子相较于轮子,没有特定的属性
}
// 后备箱
public class Trunk {
	...
}
// 汽车的后备箱
public class CarTrunk extends Trunk {
	// 汽车的后备箱相较于后备箱,没有特定的属性
}
// 汽车
public class Car {
	private List<CarWheel> wheels; // 汽车有好几个轮子
	private CarTrunk trunk; // 汽车只有一个后备箱
}

现在,假设我们要用 Mybatis 查询汽车,需要在 xml 文件中配置映射关系如下:

<resultMap id="carMap" type="Car">
	<collection property="wheels" resultMap="carWheelMap"></collection>
	<association property="trunk" resultMap="carTrunkMap"></association>
</resultMap>
<resultMap id="carWheelMap" type="Wheel">...</resultMap>
<resultMap id="carTrunkMap" type="CarTrunk">...</resultMap>

可以看到,在 <collection> 中使用的 carWheelMap 里,type 是可以为父类 Wheel 的;而在 <association> 中使用的 carTrunkMap 里,type 必须为明确的 CarTrunk,否则查询时会报错 Could not set property ……

mybatis·java
90 views
Comments
登录后评论
Sign In