mybatis使用

一、一对多映射

如某一商品规格(颜色)对应多个规格值(如红、黄等),在获取规格的同时返回对应的规格值,但商品规格对象与规格值对象有很多变量定义是相同的。

如果直接如下代码

<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>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值