Mybatis学习(11)多表之多对多查询

多对多查询指的是,一个学生可以选择很多门课程,一门课程可以有很多个学生去选择。此时两者的关系就需要一个中间表来建立,比如说选课表。

一、定义实体

由于讨论的是学生和课程之间的关系,所以,先定义实体(由于我数据库有了student 所以这里以student2代替)

public class Student2 {
	private Integer sid;
	private String sname;
	private Set<Course> course;
	
    //get和set方法
    //toString方法
	
}

然后就是课程实体

public class Course {
	private Integer cid;
	private String cname;
	private Set<Student2> students;
	
    //get 和set方法
    //toString方法
}

从以上两个实体可以看到,相互之间是包含关系。

二、定义数据库表

此时还需要一个中间表

三、定义dao接口

dao接口由于是和数据库来打交道的,所以在这里我们通过id来选择student

public interface IStudentDao {
	Student2 selectStudentById(int sid);
}

四、定义mapper映射文件IStudentDao.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.test.dao.IStudentDao">

	<resultMap type="Student2" id="studentmapper">
		<id column="sid" property="sid"/>
		<result column="sname" property="sname"/>
		<collection property="course" ofType="Course">
			<id column="cid" property="cid"/>
			<result column="cname" property="cname"/>
		</collection>
	</resultMap>

	<select id="selectStudentById" resultMap="studentmapper">
		select sid,sname,cid,cname
		from student2,middle,course
		where sid= studentid and cid= courseid and sid=#{xxx}
	</select>
</mapper>

第一:

首先从数据库中根据student2的id来选择student。但是返回的结果包含了课程,所以结果应该是一个包含很多课程的复杂结果,在这里是以studentMapper表示。

第二:

where sid= studentid and cid= courseid and sid=#{xxx}

这句话建立两个表之间的关系。

第三:

<resultMap type="Student2" id="studentmapper">
		<id column="sid" property="sid"/>
		<result column="sname" property="sname"/>
		<collection property="course" ofType="Course">
			<id column="cid" property="cid"/>
			<result column="cname" property="cname"/>
		</collection>
</resultMap>

返回的结果包含三部分,首先是sid、然后是sname、最后是course集合

五、定义测试类

    @Test
	public void testSelectMinisterById() {
		Student2 newlabel=dao.selectStudentById(2);		
		System.out.println(newlabel);
	}

结果如下

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值