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

猜你喜欢

转载自blog.csdn.net/oldcrane/article/details/45646767
今日推荐