记一次mybatis使用时造成的线上bug。

使用mybatis一对多查询时,查询出来的结果有重复。

1、resultMap:

<resultMap id="resourceCountryDtoMap" type="com.xcy.dto.ResourceCountryDto">
  <result column="resource_id" jdbcType="INTEGER" property="resourceId" />
  <result column="designer_id" jdbcType="INTEGER" property="designerId" />
  <collection  property="countryCodeList" ofType="String">
    <result column="country_code"/>
  </collection>
</resultMap>

2、更改前查询语句:

<select id="selectResourceCountryDtoByResIds" parameterType="java.util.Set" resultMap="resourceCountryDtoMap">
    select resource_id,designer_id,country_code
    from t_resource_country
    where res_id in
    <foreach collection="set" item="item" index = "index" open="(" separator="," close=")">
      #{item}
    </foreach>
  </select>

 查询日志时发现,这样查询出来的结果,实体类有两个数据相同的。

ResourceCountry(resourceId=2020, designerId=787, countryCodeList=[IN, RU])
ResourceCountry(resourceId=2020, designerId=787, countryCodeList=[IN, RU])

这就导致将数据再插入另一个表时造成resource_Id(唯一索引)冲突。

询问了一位前辈以后,大概知道造成这种现象的原因是没有做排序。应该是mybatis处理结果集时对,对没有排序的结果集可能造成重复映射为实体类。

 

3、更改后的查询:增加了order by field(resource_id)

<select id="selectResourceCountryDtoByResIds" parameterType="java.util.Set" resultMap="resourceCountryDtoMap">
  select resource_id,designer_id,country_code
  from t_resource_country
  where res_id in
  order by field(resource_id)
  <foreach collection="set" item="item" index = "index" open="(" separator="," close=")">
    #{item}
  </foreach>
</select>

4、另附他人详细解释

https://www.cnblogs.com/zemliu/archive/2013/08/16/3263053.html

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值