mybatis含有collection和association两个标签,
原基础的有id和result,id则为主键,result为对应Obj的一个映射关系。
而标签collection和association也是较为常见,
其中collection作用为一条sql statement的子查询语句查询一个集合出来设定到这个值中,
而association则通常为一个obj或单一的一个字段。
其中resultMap格式可能如下
<!--collection嵌套查询-->
<resultMap id="UserRolesMap_1" type="com.example.server.bean.User">
<id column="u_id" property="userId"/>
<result column="u_name" property="userName"/>
<!-- collection一对多,property是List属性的名字,ofType是List<>中的类型 column是传入的参数-->
<!-- select执行的是一个语句-->
<collection property="roleList"
ofType="com.example.server.bean.Role"
column="u_id"
select="findRoleListByUserId"/>
</resultMap>
<resultMap id="LabelResultMap" type="com.test.bi.bo.LabelDto">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="createtime" jdbcType="TIMESTAMP" property="createtime" />
<result column="modifytime" jdbcType="TIMESTAMP" property="modifytime" />
<collection property="LabelSubDtoList" ofType="com.test.bi.bo.LabelSubDto">
<id column="bid" jdbcType="BIGINT" property="id" />
<result column="label_id" jdbcType="BIGINT" property="labelId" />
<result column="bname" jdbcType="VARCHAR" property="name" />
<result column="bcreatetime" jdbcType="TIMESTAMP" property="createtime" />
<result column="bmodifytime" jdbcType="TIMESTAMP" property="modifytime" />
</collection>
</resultMap>
————————————————
版权声明:本文为CSDN博主「joinclear」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/joinclear/article/details/124497747
collection和association参数为本sql statement的相关字段,
即从本原有查询中获取中的行数据中的某列字段作为参数传入。
有几个常见场景可能使用collection和association查询。
collection:
1.包含子list数据,如一个用户下面包含多个子标签,一个部分下面包含哪些人。
2.递归获取菜单,按照上级菜单parent_id作为数据传入,获取递归调用的结构list,其中查询语句与collection子查询语句一般为同一个。
association:
1.数据中包含一对一关系体,如一个用户下只有一个部门,一个学生只有一组考试成绩。
2.单一字段,但查询需要单独拎出来进行查询,如较为复杂的单字段查询,再一个如group_concat某个子查询中的字段根据指定参数,而这种查询在left join或者union时难以进行查询,比如列出用户对应的考试科目以,隔开。那么这条Result的association的子查询参数就是user_id,而子查询是类似:
select group_concat(c.course_name) as courseNames
from
t_course_user cu left join
t_course c
on cu.course_id = c.id
where cu.user_id = #{userId}
最终查询结果可能是:
姓名 | 课程 |
---|---|
小红 | 数学,语文,美术 |
小明 | 英语,数学,语文 |
而对应的课程名称组合即courseNames,
而对于Obj来说,获取查询到的Obj对于子查询,也如平常查询一样,获取每个字段映射到Obj即可。