Mybatis联表查询,一对多

本文介绍了如何在MyBatis中使用一对多关联查询,通过配置collection标签来实现联表查询,使得每个老师信息下包含其对应的学生列表。在Teacher实体中声明了学生集合,并在StudentMapper中定义了查询方法。在XML映射文件中,定义了resultMap,详细解释了collection标签的属性。最后,通过测试类验证查询结果,展示了一种在MyBatis中处理一对多关系的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在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层方法并输出

查看结果:

可以看到我们的类型是一个数组类型,而数组类型中包含着老师对应的每一个学生的信息

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值