多对多查询指的是,一个学生可以选择很多门课程,一门课程可以有很多个学生去选择。此时两者的关系就需要一个中间表来建立,比如说选课表。
一、定义实体
由于讨论的是学生和课程之间的关系,所以,先定义实体(由于我数据库有了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);
}
结果如下