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

  • 相关阅读:
    git 常用命令
    spring源码-事件&监听3.6
    spring源码-国际化-3.5
    spring源码-Aware-3.4
    spring源码-BeanPostProcessor-3.3
    springboot中对yaml文件的解析
    数组Array.sort()排序的方法
    【转】js 对象按照键值(不分区大小写)排序,生成签名方法
    【转】JS常用函数整合库 lutils
    VS2017调试出现异常浏览器直接关闭的解决办法
  • 原文地址:https://www.cnblogs.com/lishuaiqi/p/10244274.html
Copyright © 2020-2023  润新知