mybatis 标签 类型为string时无法获取重复数据错误


 

1.场景:

fyq_share_house 表 和 fyq_sh_tag 表 两张表是一对多的关系, 一个楼盘对应多个标签,在实体类ShareHouse中使用

    /** * 楼盘标签 */
    private List<String> tags ;

来存放多个tag标签.

MyBatis对应的xml配置文件表示为

<collection property="tags" ofType="string">
        <constructor>
            <arg column="content"/>
        </constructor>
</collection>

通过string 的构造函数来接收数据库查找的值,

但是这样有一个缺点,就是重复的数据无法获取到.

2.原因(自己通过看别人博客总结,没有看过源码,如果有不正确的地方,还请大佬指出)

mybatis在查找数据的时候是通过主键来区分不同的数据,通过sql查找的数据结果为

 

 前面的id都是相同的,所以MyBatis会合并相同的content数据. 参考:https://blog.csdn.net/hello_xusir/article/details/53424257

3.解决

这里给出两种解决方案:

1.使用实体类

新建一个Tag类

public class Tag { private Integer id; private String content; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }

通过

private List<Tag> tags ; MyBaits中: <collection property="tags"  ofType="java.fyq.domain.Tag" select="selectTags">
            <id property="id" column="tagId"/>
        <result property="content" column="content"/>
</collection>

传统方式,List<Tag> 类型为tag而不是String 来关联主键区分content内容.

2.新建另一个select语句

(注意: select 中的 #{id} 是column 中的id 的值,不管有几个#{},值都是 column的值,也就是sql语句中  SELECT  sh.id   的值)

column 注 意 : 要 处 理 复 合 主 键 , 你 可 以 指 定 多 个 列 名 通 过 column= ” {prop1=col1,prop2=col2} ” 这种语法来传递给嵌套查询语 句。

 

                                                        

<select id="selectTags" resultType="string">
      SELECT content
      FROM fyq_sh_tag
      WHERE houseId = #{id} 
</select>
<collection property="tags" column="id" ofType="string" select="selectTags">

</collection>

collection 标签中 的column属性设置为 新建的select语句中主键来区分content.

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM