Mybatis中查询复杂映射结构

一、结果包含子列表

0.Bean

1
2
3
4
5
public class School{
//其他略
private String schoolName;
private List<Student> studentList;
}

1.定义resultMap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<resultMap type="School" id="SchoolResult">
<result property="id" column="id"/>
<result property="schoolName" column="school_name" />
<result property="createUser" column="create_user"/>
<result property="createUserId" column="create_user_id"/>
<result property="createTime" column="create_time"/>
</resultMap>

<resultMap type="Student" id="StudentResult">
<result property="id" column="id"/>
<result property="schoolId" column="school_id"/>
<result property="studentName" column="student_name" />
<result property="createUser" column="create_user"/>
<result property="createUserId" column="create_user_id"/>
<result property="createTime" column="create_time"/>
</resultMap>

<resultMap id="ShcoolStudentResult" type="Student" extends="SchoolResult">
<collection property="studentList" notNullColumn="sub_id" javaType="java.util.List" resultMap="StudentResult"/>
</resultMap>

2.select语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<select id="selectSchoolStudentById" parameterType="String"
resultMap="ShcoolStudentResult">
select a.id,
a.create_user,
a.create_user_id,
a.create_time,
a.school_name,
b.id as sub_id,
b.create_user as sub_create_user,
b.create_user_id as sub_create_user_id,
b.create_time as sub_create_time,
b.student_name as sub_student_name,
b.school_id as sub_school_id,
from school a
left join student b on b.school_id = a.id
where a.id = #{id}
</select>

3.使用

1
2
School schoolInfo = SchoolMapper.selectSchoolStudentById(id);
//返回的School对象就带有Student列表信息

4.注意事项!

PageHepler分页插件不支持嵌套结果映射
[参考文档]: https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/Important.md

[参考解决方案]: https://blog.csdn.net/weixin_41869361/article/details/116427385

二、结果包含子对象


Mybatis中查询复杂映射结构
http://blog.jingxiang.ltd/2023/03/30/Mybatis中查询复杂映射结构/
作者
yemangran
发布于
2023年3月30日
许可协议