一、一对多映射
如某一商品规格(颜色)对应多个规格值(如红、黄等),在获取规格的同时返回对应的规格值,但商品规格对象与规格值对象有很多变量定义是相同的。
如果直接如下代码
<resultMap id="allMap" type="SpecBean">
<id column="spec_id" property="specId" />
......
<collection property="specVals" resultMap="specDetailMapper.BaseResultMap" ></collection>
</resultMap>
则会因为两个对象的的字段有重复,即使某个规格下没有规格值,也会导致有规格值返回。
解决办法:
<collection property="specVals" resultMap="specDetailMapper.BaseResultMap" columnPrefix="detail_"></collection>
采用columnPrefix区分规格字段与规格值字段,同时sql中返回的字段名也对应用前缀重命名spec_detail.spec_id as detail_spec_id
二、鉴别器discriminator的使用
比如商品是否定义会员价,如果定义了会员价,查询商品信息时返回会员价列表,没设置会员价时就不返回会员价列表,
<resultMap id="itemMemberPriceMap" type="ItemBean">
<id column="goods_item_id" property="goodsItemId" />
<result column="goods_id" property="goodsId" />
<result column="isMemberDiscount" property="isMemberDiscount" />
<!-- 根据 是否设置会员价标志字段isMemberDiscount,, 判断是否返回会员价-->
<discriminator javaType="int" column="isMemberDiscount">
<case value="2" resultMap="memberPriceMap">
</case>
</discriminator>
</resultMap>
<resultMap id="memberPriceMap" type="ItemBean" extends="itemMemberPriceMap">
<collection property="memberPriceList" resultMap="itemReleCardMap" />
</resultMap>
<resultMap id="itemReleCardMap" type="itemReleCardBean">
<id column="id" property="id" />
<result column="card_id" property="cardId" />
<result column="price" property="price" />
</resultMap>
三、根据条件update表时,返回已更新记录主键信息
使用selectKey关键字,执行更新之前先获取待更新的记录:
<selectKey keyProperty="idsStr" resultType="string" order="BEFORE">
SELECT GROUP_CONCAT(id) as idsStr
from t_test
where 1=1 and //#{condition_sql}
</selectKey>