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.
