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