Mybatis联表查询,一对多

导读:本篇文章讲解 Mybatis联表查询,一对多,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

在Mybatis中实现一对多来进行联表查询需要使用到collection标签,那么我们首先看一下我们的数据库表和字段。

Student

Mybatis联表查询,一对多

Teacher

Mybatis联表查询,一对多

我们的思路是,查询出每个老师教的学生,查询出来的结果是每个老师对应的学生是一个数组,数组里面是每一条学生的信息

然后我们需要在Teacher的实体中声明学生的信息(TableField表示该字段不属于数据库字段)

Mybatis联表查询,一对多

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

查看结果:

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之家整理,本文链接:https://www.bmabk.com/index.php/post/48512.html

(0)
小半的头像小半

相关推荐

极客之家——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!