zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    Scala编程基础
    大数据学习环境搭建(CentOS6.9+Hadoop2.7.3+Hive1.2.1+Hbase1.3.1+Spark2.1.1)
    hadoop2.7.3编译,支持snappy、bzip2本地压缩
    ABAP非Unicode系统中字符串拼接(CONCATENATE)时吃字符问题
    Hadoop学习笔记
    HIVE开发总结
    中文字符截取乱码问题
    替换空字符NULL(字符编码为0的字符)
    Generate Time Data(普通日期主数据)
    Generate Time Data(财务日期主数据)
  • 原文地址:https://www.cnblogs.com/lishuaiqi/p/10244274.html