Mybatis:resultMap元素中的<collection/>标签的使用

发布时间 2023-07-31 15:25:50作者: 勇敢-的心

resultMap元素是Mybatis中非常强大的元素,它可以将查询到的复杂数据映射到一个结果集当中。

resultMap元素:

<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="com.xxx.yyy.entity.AbsAuthority">
<id column="id" property="id" />
<result column="code" property="code" />
<result column="name" property="name" />
<!--注意:这里有一个递归的子查询,并且返回的是一个子对象.-->
<collection column="id" property="children" ofType="com.xxx.yyy.entity.AbsAuthority" select="getAuthByPid" >
</collection>
</resultMap>
备注:
collection标签的使用说明:<collection property="pojo的集合属性" ofType="集合中的pojo对象">
比如,上面的代码中property为children,在AbsAuthority类中,children的集合属性为:private List<SysAuthority> children;
说明这是一个嵌套的集合对象,是一个一对多的嵌套子查询;
ofType:定义的就是集合中的完整的对象名称;
select:定义的是嵌套的查询语句;说明这里的collection是一个嵌套查询,
<!-- 递归子查询:根据父id查询其所有的孩子.-->
<select id="getAuthByPid" parameterType="java.lang.Long" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"></include>
from abc_auth
where pid = #{id} and del_flag = 0
order by sort
</select>