前言

  • Mybatis 一对一,使用 association 标签
  • Mybatis 一对多,使用 collection 标签
  • 本文主要说明 collection 实现一对多关联。使用 association 实现一对一关联,参考这里

介绍

中文参考英文参考

collection 的用法分为2种:

  • 嵌套 Select 查询(Nested Select for Collection)
  • 嵌套结果映射(Nested Results for Collection)

嵌套 Select 查询方式:Collection 实现一对多关联

<mapper namespace="...">
	<resultMap type="XX" id="XXMap">
		<result property="id" column="xx_id"/>  
		<result property="name" column="xx_name"/> 
		<result property="xxxId" column="xxx_id"/> 
		...
		
		<collection property="xxxList" javaType="ArrayList" column="{id = xxx_id}" select="getXXXList"/>  
	</resultMap>
	<resultMap type="XXX" id="XXXMap">
		<result property="id" column="xxx_id"/>  
		<result property="name" column="xxx_name"/> 
		...
	</resultMap>
	
	<select id="getXXXList" parameterType="map" resultMap="xxxMap">
	    select * from xxx where xxx_id=#{id}
	</select>
</mapper>

嵌套结果映射方式

略。

嵌套 Select 查询方式:遇到复合主键是怎么办?

<mapper namespace="...">
	<resultMap type="XX" id="XXMap">
		<id property="id" column="colid"/>  
		<id property="name" column="colname"/> 
		 
		<collection property="list" javaType="ArrayList" column="{id = colid,name=colname}" select="getSubXXX"/>  
	</resultMap>
	
	<select id="getSubXXX" parameterType="map" resultMap="SubXXXMap">
	    select * from sub_xxx where xxx_id=#{id} and xxx_name=#{name}
	</select>
</mapper>
  • column="{id=colid, name=colname}": id+name为符合主键
  • id、name为别名/变量名
  • colid、colname为数据库中表的列名
  • getSubXXX中,直接使用别名/变量名即可,比如:#{id}

嵌套 Select 查询方式:向 collection / 嵌入的 Select 查询 / 子查询 传参数

<mapper namespace="...">
	<resultMap type="XX" id="XXMap">
		<id property="id" column="colid"/>  
		<id property="name" column="colname"/> 
		 
		<collection property="list" javaType="ArrayList" column="{i=colid, security=params_security}" select="getSubXXX"/>  
	</resultMap>
	
	<select id="getXXX" parameterType="map" resultMap="XXMap">
	    select *, ${security_from_param} as params_security 
	    from xxx where xxx_id=#{id}
	</select>
	<select id="getSubXXX" parameterType="map" resultMap="SubXXXMap">
	    select * from sub_xxx where xxx_id=#{id}
	    <where>
	    	<if test="security != 1"> and secrecy_status = 0</if>
	    </where>
	</select>
</mapper>
  • ${security_from_param}${}是字符串拼接操作符
  • ${security_from_param} as params_security :在 Select 查询中拼接出一个新列
  • id="getXXX" 的 Select 查询中,多了名为params_security的列,该列的值从传入参数中获取。
  • 通过 collection column 属性,将 params_security 列转化为 security 参数传入 id="getSubXXX" 的 Select 查询中
  • id="getSubXXX" 的 Select 查询中,从上下文参数中获取并使用父级查询传入的参数。
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐