一个班级配置一个教师,一个班级有多个学生。
关系:
要求查询到的班级带老师信息和该班学生信息。
要求查询的班级信息只带老师的信息,不带学生信息。
执行SQL语句,创建教师表t_teacher:
CREATE TABLE `t_teacher` (
`t_id` int(11) NOT NULL AUTO_INCREMENT,
`t_name` varchar(20) DEFAULT NULL,
PRIMARY KEY (`t_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;
执行SQL语句,插入3条记录:
INSERT INTO `t_teacher` VALUES ('1', '刘晓云');
INSERT INTO `t_teacher` VALUES ('2', '郑同华');
INSERT INTO `t_teacher` VALUES ('3', '李明军');
执行SQL语句,创建班级表t_class:
CREATE TABLE `t_class` (
`c_id` int(11) NOT NULL AUTO_INCREMENT,
`c_name` varchar(20) DEFAULT NULL,
`teacher_id` int(11) DEFAULT NULL,
PRIMARY KEY (`c_id`),
KEY `fk_teacher_id` (`teacher_id`),
CONSTRAINT `fk_teacher_id` FOREIGN KEY (`teacher_id`) REFERENCES `t_teacher` (`t_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;
执行SQL语句,插入3条记录:
INSERT INTO `t_class` VALUES ('1', '2021软件1班', '3');
INSERT INTO `t_class` VALUES ('2', '2021软件2班', '2');
INSERT INTO `t_class` VALUES ('3', '2021软件3班', '1');
执行SQL语句,创建学生表t_student:
CREATE TABLE `t_student` (
`s_id` int(11) NOT NULL AUTO_INCREMENT,
`s_name` varchar(30) DEFAULT NULL,
`s_gender` varchar(10) DEFAULT NULL,
`s_age` int(11) DEFAULT NULL,
`class_id` int(11) DEFAULT NULL,
PRIMARY KEY (`s_id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4;
执行SQL语句,插入9条记录:
INSERT INTO `t_student` VALUES ('1', '佟大为', '男', '20', '1');
INSERT INTO `t_student` VALUEs ('2', '李方玉', '女', '19', '1');
INSERT INTO `t_student` VALUES ('3', '郑大林', '男', '19', '2');
INSERT INTO `t_student` VALUES ('4', '温晓辉', '男', '18', '1');
INSERT INTO `t_student` VALUES ('5', '吴文静', '女', '19', '2');
INSERT INTO `t_student` VALUES ('6', '肖文艳', '女', '18', '3');
INSERT INTO `t_student` VALUES ('7', '杨文军', '男', '20', '3');
INSERT INTO `t_student` VALUES ('8', '唐雨涵', '女', '19', '2');
INSERT INTo `t_student` VALUES ('9', '金雨欣', '女', '20', '2');
在net.army.mybatis.bean包里创建Teacher类
代码如下:
package net.army.mybatis.bean;
/**
* 作者:梁辰兴
* 日期:2023/4/18
* 功能:教师实体类
*/
public class Teacher {
private int id;
private String 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 "Teacher{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
在net.army.mybatis.bean包里创建Student类
代码如下:
package net.huawei.mybatis.bean;
/**
* 功能:学生实体类
* 作者:梁辰兴
* 日期:2023年04月18日
*/
public class Student {
private int id;
private String name;
private String gender;
private int age;
private Clazz clazz;
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 String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Clazz getClazz() {
return clazz;
}
public void setClazz(Clazz clazz) {
this.clazz = clazz;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", gender='" + gender + '\'' +
", age=" + age +
", clazz=" + clazz.getName() +
'}';
}
}
注意:
- 学生表的第5个字段是class_id(作为外键),但是学生实体类的第5个属性并不是班级编号,而是班级类(clazz),此时尚未创建,因此代码会报错。
- toString()方法里,输出的不是班级实体类的完整信息,而是班级名称,通过clazz.getName()获取。
在net.army.mybatis.bean包里创建Clazz类
代码如下:
package net.army.mybatis.bean;
import java.util.List;
/**
* 作者:梁辰兴
* 日期:2023/4/18
* 功能:班级实体类
*/
public class Clazz {
private int id;
private String name;
private Teacher teacher;
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 "Clazz{" +
"id=" + id +
", name='" + name + '\'' +
", teacher=" + teacher +
", students=" + students +
'}';
}
}
注意:toString()方法里,输出的不是教师实体类的完整信息,而是教师姓名,通过teacher.getName()获取。
在resources/mapper目录里创建班级映射器配置文件ClazzMapper.xml
代码如下:
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="net.army.mybatis.mapper.ClazzMapper">
<select id="findById" parameterType="int" resultMap="clazzMap1">
SELECT * FROM t_class
INNER JOIN t_teacher ON t_class.teacher_id = t_teacher.t_id
INNER JOIN t_student ON t_class.c_id = t_student.class_id
WHERE c_id = #{id};
select>
<resultMap id="clazzMap1" type="Clazz">
<result property="id" column="c_id"/>
<result property="name" column="c_name"/>
<association property="teacher" javaType="Teacher" column="teacher_id">
<result property="id" column="t_id"/>
<result property="name" column="t_name"/>
association>
<collection property="students" ofType="Student">
<result property="id" column="s_id"/>
<result property="name" column="s_name"/>
<result property="gender" column="s_gender"/>
<result property="age" column="s_age"/>
<association property="clazz" javaType="Clazz" column="class_id">
<result property="name" column="c_name"/>
association>
collection>
resultMap>
<select id="findAll" resultMap="clazzMap2">
SELECT * FROM t_class;
select>
<resultMap id="clazzMap2" type="Clazz">
<result property="id" column="c_id"/>
<result property="name" column="c_name"/>
<association property="teacher" javaType="Teacher" column="teacher_id" select="getTeacher"/>
resultMap>
<select id="getTeacher" resultType="Teacher">
SELECT t_id id, t_name name FROM t_teacher WHERE t_id = #{id};
select>
mapper>
在配置文件里配置班级、教师与学生实体类别名,以及班级映射器配置文件
在net.army.mybatis.mapper包里创建ClazzMapper接口
代码如下:
package net.army.mybatis.mapper;
import net.army.mybatis.bean.Clazz;
import java.util.List;
/**
* 作者:梁辰兴
* 日期:2023/4/18
* 功能:班级映射器接口
*/
public interface ClazzMapper {
Clazz findById(int id); // 按编号查询班级记录
List<Clazz> findAll(); // 查询全部班级记录
}
在test/java目录的net.army.mybatis.mapper包里创建TestClazzMapper类
代码如下:
package net.army.mybatis.mapper;
import net.army.mybatis.bean.Clazz;
import net.army.mybatis.bean.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
/**
* 功能:测试班级映射器
* 作者:梁辰兴
* 日期:2023/4/18
*/
public class TestClazzMapper {
private SqlSession sqlSession; // SQL会话
private ClazzMapper clazzMapper; // 班级映射器
@Before
public void init() {
try {
// 读取MyBatis配置文件
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
// 基于MyBatis配置文件构建SQL会话工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
// 利用SQL会话工厂获取SQL会话
sqlSession = factory.openSession();
// 利用SQL会话获取班级映射器对象
clazzMapper = sqlSession.getMapper(ClazzMapper.class);
// 提示用户SQL会话创建成功
System.out.println("SQL会话创建成功~");
} catch (IOException e) {
e.printStackTrace();
}
}
@Test // 按编号查询班级(带教师信息和学生信息)
public void testFindById() {
// 查询id为1的班级信息
int id = 1;
Clazz clazz = clazzMapper.findById(id);
// 判断是否查询成功
if (clazz != null) {
// 打印班级信息
System.out.println(clazz);
// 打印班级学生信息
System.out.println("班级编号为[" + id + "]的学生:");
List<Student> students = clazz.getStudents();
students.forEach(student -> System.out.println(student));
} else {
System.out.println("编号为[" + id + "]的班级不存在~");
}
}
@Test // 查询全部班级信息
public void testFindAll() {
// 查询全部班级
List<Clazz> clazzes = clazzMapper.findAll();
// 输出全部班级
clazzes.forEach(clazz -> System.out.println(clazz));
}
@After
public void destroy() {
// 关闭SQL会话
sqlSession.close();
// 提示用户SQL会话关闭
System.out.println("SQL会话已经关闭~");
}
}