2.11 Mybatis——多对多集合映射处理(1)

本文详细介绍了如何使用MyBatis实现通过学生ID查询其关联的多个教师信息。通过在Student实体类中定义Teacher集合属性,配合StudenMapper.xml中的<collection>标签,以及TeacherDao的查询方法,实现了从数据库中获取并映射学生和教师的关联数据。在测试中成功打印出了学生及其关联的教师信息。
摘要由CSDN通过智能技术生成

1.通过学生查询教师信息,使用一对多的第一种方法。

2.实例展示:

问题描述

通过学生sid查询老师信息。

数据库e-r图

 代码实现

学生实体类Student.java:将教师实体类的集合作为学生的属性。

    private List<Teacher> teachers;

    public List<Teacher> getTeachers() {
        return teachers;
    }

    public void setTeachers(List<Teacher> teachers) {
        this.teachers = teachers;
    }

StuentDao.java层方法:

//通过学生sid查出老师
Student getStudentById(int sid);

StuddentMapper.xml文件核心内容:

 collection标签内column属性值为传入下句sql语句的字段属性名
                           property属性值为student实体类中teacher集合的属性名

<mapper namespace="com.zx.dao.StudentDao">

    <select id="getStudentById" resultMap="studentResult">
        select * from student where sid=#{sid}
    </select>
    <resultMap id="studentResult" type="com.zx.pojo.Student">
        <id column="sid" property="sid"></id>
        <result column="sname" property="sname"></result>
        <!--集合映射
                collection标签内column属性值为传入下句sql语句的字段属性名。
                                property属性值为student实体类中teacher集合的属性名。
        -->
        <collection column="sid" property="teachers" select="com.zx.dao.TeacherDao.getTeachersBySid" ofType="com.zx.pojo.Teacher" ></collection>
    </resultMap>
</mapper>

TeacherDao.java层方法:

List<Teacher> getTeachersBySid(int sid);

TeacherMapper文件:通过中间表查询满足条件的教师信息

<mapper namespace="com.zx.dao.TeacherDao">

    <!--通过学生sid找老师——通过中间表-->
    <select id="getTeachersBySid" resultType="com.zx.pojo.Teacher">
        select * from teacher where tid in (select tid from student_teacher where sid=#{sid})
    </select>

</mapper>

 Mybatis-config.xml添加sql映射:

<mappers>
        <mapper resource="com/zx/dao/StudentMapper.xml"></mapper>
        <mapper resource="com/zx/dao/TeacherMapper.xml"></mapper>
</mappers>

运行测试:

public class StudentDaoTest {

    @Test
    public void getStudentByIdTest(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        StudentDao studentDao = sqlSession.getMapper(StudentDao.class);

        Student student = studentDao.getStudentById(2);
        System.out.println(student);
        //通过Teachers属性的get方法读取教师信息
        System.out.println(student.getTeachers());
    }
}

测试结果:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值