Mybatis中 collection 和 association 标签 的区别

发布时间 2023-11-03 15:29:54作者: 爱喝茶的安迪


版权声明:本文为CSDN博主「时夏゛」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/XikYu/article/details/132761255

<collection> 和 <association> 是 MyBatis 中用于定义映射关系的标签,它们的区别如下:

目标对象类型:

<collection> 用于表示集合属性,即一个属性对应多个关联对象。
<association> 用于表示关联属性,即一个属性对应一个关联对象。
关联关系处理:

<collection> 用于处理一对多或多对多的关联关系,其中集合属性将包含对应的关联对象的集合。
<association> 用于处理一对一或多对一的关联关系,其中关联属性将包含对应的关联对象。
SQL 查询方式:

<collection> 通常需要执行额外的 SQL 查询来获取关联对象的数据,通常需要使用 select 子句指定查询语句。
<association> 通常会在关联对象的查询语句中使用 join 操作,将关联对象的数据与当前对象的数据一起查询出来。
映射方式:

<collection> 通常在结果映射中使用嵌套的 <resultMap> 定义,以映射关联对象的属性。
<association> 通常在结果映射中使用 <result> 标签定义,以映射关联对象的属性。
总结起来,<collection> 用于表示一对多或多对多的集合属性,并需要执行额外的 SQL 查询来获取关联对象的数据,而 <association> 用于表示一对一或多对一的关联属性,并使用 join 操作将关联对象的数据与当前对象一起查询出来。

示例:

 

 

<resultMap id="CommentRecursionMap" type="com.ly.cloud.vo.app.HdplTreeVO">
<id column="pkid" property="pkid"/>
<result column="xsid" property="xsid"/>
<result column="xm" property="xm"/>
<result column="plid" property="plid"/>
<result column="hfplid" property="hfplid"/>
<result column="fjid" property="fjid"/>
<collection property="replyData" select="selectCommentRecursionDataByPlid" column="{plid=pkid}"/>
</resultMap>
<!--先查询自主评论的数据,在递归查询回复评论数据-->
<select id="selectCommentRecursionDataByHdid" resultMap="CommentRecursionMap">
select
t.pkid,

t.plid,

from zhxg_gqt_dekt_hdpl t
left join zhxg_gqt_dekt_grxx grxx on grxx.yhid = t.xsid
where t.pllx = '1' and t.hdid = #{hdid}

</select>
<!--配合selectCommentRecursionDataByHdid使用-->
<select id="selectCommentRecursionDataByPlid" resultMap="CommentRecursionMap">
select
t.pkid,
t.plid
from zhxg_gqt_dekt_hdpl t
left join zhxg_gqt_dekt_grxx grxx on grxx.yhid = t.xsid
where nvl(t.hfplid,t.plid) = #{plid}

</select>