在Mybatis中实现一对多来进行联表查询需要使用到collection标签,那么我们首先看一下我们的数据库表和字段。
Student
Teacher
我们的思路是,查询出每个老师教的学生,查询出来的结果是每个老师对应的学生是一个数组,数组里面是每一条学生的信息
然后我们需要在Teacher的实体中声明学生的信息(TableField表示该字段不属于数据库字段)
然后在StudentMapper中声明一个方法
public interface StudentMapper extends BaseMapper<Student> {
List<Teacher> queryStudentsByTeachers();
}
注:我们需要在StudentMapper.xml中进行查询
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ywt.mybatisplus.mapper.StudentMapper">
<resultMap id="studentResultMap" type="com.ywt.mybatisplus.model.Student">
<id column="id" property="id"/>
<result column="s_name" property="sName"/>
<result column="t_id" property="tId"/>
</resultMap>
<resultMap id="teacherResultMap" type="com.ywt.mybatisplus.model.Teacher">
<id column="teacherId" property="id"/>
<result column="t_name" property="tName"/>
<collection property="studentList"
resultMap="studentResultMap"
javaType="java.util.List"/>
</resultMap>
<select id="queryStudentsByTeachers" resultMap="teacherResultMap">
SELECT
t.id AS teacherId,
t.t_name,
s.id,
s.s_name,
s.t_id
FROM
teacher t
LEFT JOIN student s ON t.id = s.t_id
</select>
</mapper>
在StudentMapper.xml定义老师的resultMap,id可以随便取,type是老师的实体类,把字段声明,定义collection标签。
那我们来看一下collection标签中的属性都代表什么:
property:我们在Teacher实体中定义的Student集合
resultMap:映射到Student的resultMap的id
javaType:类型是list
然后我们在测试类中测试看看返回的数据是否和我们预期的一样
@SpringBootTest
class MybatisPlusApplicationTests {
@Autowired
private StudentMapper studentMapper;
@Test
void queryWrapper(){
List<Teacher> teachers = studentMapper.queryStudentsByTeachers();
teachers.forEach(System.out::println);
}
调用dao层方法并输出
查看结果:
可以看到我们的类型是一个数组类型,而数组类型中包含着老师对应的每一个学生的信息