student表
teacher表
一个老师对应多个学生
Teacher.java
package org.example.pojo;
/**
* @author aRu
* @date 2021/3/17 20:21
*/
public class Teacher {
private int id;
private String name;
public Teacher() {
}
public Teacher(int id, String name) {
this.id = id;
this.name = 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 + '\'' +
'}';
}
}
Student.java
一个老师对应多个学生,在学生类中写上Teacher teacher
package org.example.pojo;
/**
* @author aRu
* @date 2021/3/17 20:20
*/
public class Student {
private int id;
private String name;
private Teacher teacher;
public Student() {
}
public Student(int id, String name, Teacher teacher) {
this.id = id;
this.name = name;
this.teacher = teacher;
}
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;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", teacher=" + teacher +
'}';
}
}
StudentMapper.java
public interface StudentMapper {
//查询所有的学生信息 以及对应的老师的信息
public List<Student> getStudent();
}
- 在查询学生时,学生中包含了Teacher这个类,查询的resultType比较复杂 ,所以采用resultMap的形式
- sql语句中将学生表、教师表中s.id s.name t.name字段起别名为sid sname tname
select s.id sid, s.name sname, t.name tname
from mybatis.student s,mybatis.teacher t
where s.tid=t.id;
-
resultMap的编写
在上一步中三个关键的数据库字段名被起别名,与原来java中的属性名不一致,所以要一一对应一下;
对于一般的属性 用
result
标签对于类来说 用 association 标签 在java实体类中属性名property为teacher , javaType="Teacher"
而原来java实体类中属性名name对于起别名后 的tname
StudentMapper.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">
<!--namespace 是要绑定的类的路径-->
<mapper namespace="org.example.dao.StudentMapper">
<!--按照结果嵌套处理-->
<select id="getStudent" resultMap="StudentTeacher">
select s.id sid, s.name sname, t.name tname
from mybatis.student s,mybatis.teacher t
where s.tid=t.id;
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
</mapper>