mybatis <collection>标签 类型为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.

 

posted @   随意的马蒂洛克  阅读(4615)  评论(2编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示