MyBatis 一对多映射的一个小坑

下午写个报表,要那两个基础业务对象  city 和 zone,1:n,准备用MyBatis一对多映射,一次性获取,组装成 list of City,每个City对象中包含相应的Zone 列表


一开始的MyBatis配置如下:

<resultMap id="cityWithZone" type="City">
	<id property="id"/>
	<result property="name"/>
	<result property="active"/>
 	<collection property="zones" ofType="DeliveryZone" columnPrefix="zone_">
		<id property="id" column="id" />
		<result property="name" column="name"/>
		<result property="mode" column="mode"/>
		<result property="active" column="active"/>
	</collection>
</resultMap>

<select id="findAllActiveWithZone" resultMap="cityWithZone">
	SELECT
		C.id, C.name, C.active, 
		Z.id zone_id, Z.name zone_name, Z.active zone_active, Z.mode zone_mode
	FROM t_delivery_zone Z left outer join t_city C on Z.city_id=C.id 
	WHERE Z.active='Y' and C.active='Y'
	ORDER BY C.sort_no desc
</select>

数据库中有符合条件的 City 5个,Zone 22个,这样只能得到一个size为22的列表,每个对象都是空。


最后发现,在这种情况下,必须显式指定 column 的名字,即使它和property的名字完全相同:

<resultMap id="cityWithZone" type="City">
	<id property="id" column="id"/>
	<result property="name" column="name"/>
	<result property="active" column="active"/>
	<collection property="zones" ofType="DeliveryZone" columnPrefix="zone_">
		<id property="id" column="id" />
		<result property="name" column="name"/>
		<result property="mode" column="mode"/>
		<result property="active" column="active"/>
	</collection>
</resultMap>

黄鹤 2015-05-11

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值