[TOC]
# 一对多关联
根据classId查询对应的班级信息,包括学生,老师
## 一、创建表和数据
一对一关联查询中,已经创建了班级表和教师表,因此这里再创建一张学生表。
~~~
CREATE TABLE student(
s_id INT PRIMARY KEY AUTO_INCREMENT,
s_name VARCHAR(20),
class_id INT
);
INSERT INTO student(s_name, class_id) VALUES('student_A', 1);
INSERT INTO student(s_name, class_id) VALUES('student_B', 1);
INSERT INTO student(s_name, class_id) VALUES('student_C', 1);
INSERT INTO student(s_name, class_id) VALUES('student_D', 2);
INSERT INTO student(s_name, class_id) VALUES('student_E', 2);
INSERT INTO student(s_name, class_id) VALUES('student_F', 2);
~~~
## 二、定义实体类
1、Student类
~~~
package com.ntqingniao.mybatis.entity;
/**
* 定义student表所对应的实体类
*
* @author CUI
*
*/
public class Student {
// 定义属性,和student表中的字段对应
private int id; // id===>s_id
private String name; // name===>s_name
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + "]";
}
}
~~~
2、修改Classes类,添加一个List<Student> students属性,使用一个List<Student>集合属性表示班级拥有的学生,如下:
~~~
package com.ntqingniao.mybatis.entity;
import java.util.List;
/**
* 定义class表对应的实体类
*
* @author CUI
*
*/
public class Classes {
// 定义实体类的属性,与class表中的字段对应
private int id; // id===>c_id
private String name; // name===>c_name
/**
* class表中有一个teacher_id字段,所以在Classes类中定义一个teacher属性,
* 用于维护teacher和class之间的一对一关系,通过这个teacher属性就可以知道这个班级是由哪个老师负责的
*/
private Teacher teacher;
// 使用一个List<Student>集合属性表示班级拥有的学生
private List<Student> students;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
@Override
public String toString() {
return "Classes [id=" + id + ", name=" + name + ", teacher=" + teacher
+ ", students=" + students + "]";
}
}
~~~
## 三、修改 sql 映射的 ClassMapper 接口
添加如下方法:
~~~
package com.ntqingniao.mybatis.mapping;
import com.ntqingniao.mybatis.entity.*;
public interface ClassMapper {
/**
* 方式一:嵌套结果(根据班级id查询班级信息 )
*
* @param id
* @return
*/
public Classes getClass(int id);
/**
* 方式二:嵌套查询(根据班级id查询班级信息 )
*
* @param id
* @return
*/
public Classes getClass2(int id);
/**
* 方式一:嵌套结果(根据classId查询对应的班级信息,包括学生,老师 )
* @param id
* @return
*/
public Classes getClass3(int id);
/**
* 方式二:嵌套查询(根据classId查询对应的班级信息,包括学生,老师 )
* @param id
* @return
*/
public Classes getClass4(int id);
}
~~~
## 四、修改 sql 映射文件 classMapper.xml
添加如下的 SQL 映射信息:
~~~
<!--
根据classId查询对应的班级信息,包括学生,老师
-->
<!--
方式一: 嵌套结果: 使用嵌套结果映射来处理重复的联合结果的子集
SELECT * FROM class c, teacher t,student s WHERE c.teacher_id=t.t_id AND c.C_id=s.class_id AND c.c_id=1
-->
<select id="getClass3" parameterType="int" resultMap="ClassResultMap3">
select * from class c, teacher t,student s where c.teacher_id=t.t_id and c.C_id=s.class_id and c.c_id=#{id}
</select>
<resultMap type="com.ntqingniao.mybatis.entity.Classes" id="ClassResultMap3">
<id property="id" column="c_id"/>
<result property="name" column="c_name"/>
<association property="teacher" column="teacher_id" javaType="com.ntqingniao.mybatis.entity.Teacher">
<id property="id" column="t_id"/>
<result property="name" column="t_name"/>
</association>
<!-- ofType指定students集合中的对象类型 -->
<collection property="students" ofType="com.ntqingniao.mybatis.entity.Student">
<id property="id" column="s_id"/>
<result property="name" column="s_name"/>
</collection>
</resultMap>
<!-- 方式二:嵌套查询:通过执行另外一个SQL映射语句来返回预期的复杂类型
SELECT * FROM class WHERE c_id=1;
SELECT * FROM teacher WHERE t_id=1 //1 是上一个查询得到的teacher_id的值
SELECT * FROM student WHERE class_id=1 //1是第一个查询得到的c_id字段的值
-->
<select id="getClass4" parameterType="int" resultMap="ClassResultMap4">
select * from class where c_id=#{id}
</select>
<resultMap type="com.ntqingniao.mybatis.entity.Classes" id="ClassResultMap4">
<id property="id" column="c_id"/>
<result property="name" column="c_name"/>
<association property="teacher" column="teacher_id" javaType="com.ntqingniao.mybatis.entity.Teacher" select="getTeacher2"></association>
<collection property="students" ofType="com.ntqingniao.mybatis.entity.Student" column="c_id" select="getStudent"></collection>
</resultMap>
<select id="getTeacher2" parameterType="int" resultType="com.ntqingniao.mybatis.entity.Teacher">
SELECT t_id id, t_name name FROM teacher WHERE t_id=#{id}
</select>
<select id="getStudent" parameterType="int" resultType="com.ntqingniao.mybatis.entity.Student">
SELECT s_id id, s_name name FROM student WHERE class_id=#{id}
</select>
~~~
## 五、编写测试代码
~~~
package com.ntqingniao.mybatis.test;
import java.io.InputStream;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.ntqingniao.mybatis.entity.Classes;
import com.ntqingniao.mybatis.mapping.ClassMapper;
public class Test3 {
public static void main(String[] args) {
// mybatis的配置文件
String resource = "conf.xml";
// 使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)
InputStream is = Test.class.getClassLoader().getResourceAsStream(
resource);
// 构建sqlSession的工厂
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder()
.build(is);
// 使用MyBatis提供的Resources类加载mybatis的配置文件(它也加载关联的映射文件)
// Reader reader = Resources.getResourceAsReader(resource);
// 构建sqlSession的工厂
// SqlSessionFactory sessionFactory = new
// SqlSessionFactoryBuilder().build(reader);
// 创建能执行映射文件中sql的sqlSession
SqlSession session = sessionFactory.openSession();
// 通过getMapper()方法获取ClassMapper接口
ClassMapper classMapper = session.getMapper(ClassMapper.class);
Classes classes = new Classes();
/** 根据id,查询用户信息 **/
// 查询class表中id为1的记录,执行查询操作,将查询结果自动封装成Classes返回
classes = classMapper.getClass3(1);
// 打印结果:Classes [id=1, name=class_a, teacher=Teacher [id=1, name=teacher1], students=[Student [id=1, name=student_A], Student [id=2, name=student_B], Student [id=3, name=student_C]]]
System.out.println(classes);
/** 根据id,查询用户信息 **/
// 查询class表中id为1的记录
classes = classMapper.getClass4(1);
// 打印结果:Classes [id=1, name=class_a, teacher=Teacher [id=1, name=teacher1], students=[Student [id=1, name=student_A], Student [id=2, name=student_B], Student [id=3, name=student_C]]]
System.out.println(classes);
// 使用SqlSession执行完SQL之后需要关闭SqlSession
session.close();
}
}
~~~
## 六、一对多关联查询总结
MyBatis 中使用 collection 标签来解决一对多的关联查询,ofType 属性指定集合中元素的对象类型。