一对多处理
一个老师拥有多个学生(对老师而言,就是一对多的关系)
1、新建实体类
Teacher
package com.sw.pojo;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* @Author suaxi
* @Date 2020/12/13 10:55
*/
@Data
public class Teacher implements Serializable {
private int id;
private String name;
//一个老师对应多个学生
private List<Student> students;
}
Student
package com.sw.pojo;
import lombok.Data;
import java.io.Serializable;
/**
* @Author suaxi
* @Date 2020/12/13 10:55
*/
@Data
public class Student implements Serializable {
private int id;
private String name;
private int tid;
}
2、TeacherMapper.xml配置(两种方式)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sw.dao.TeacherMapper">
<!--按结果集嵌套处理-->
<select id="findTeacherById" resultMap="TeacherStudent">
select s.id sid,s.name sname,t.id tid ,t.name tname
from student s,teacher t
where s.tid = t.id and t.id = #{tid};
</select>
<resultMap id="TeacherStudent" type="teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<!--
集合使用 collection
javaType="" 指定属性的类型
集合中的泛型信息,使用 ofType 获取
-->
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
<!--按照查询嵌套处理-->
<select id="findTeacherById2" resultMap="TeacherStudent2">
select * from teacher where id = #{tid};
</select>
<resultMap id="TeacherStudent2" type="Teacher">
<collection property="students" javaType="ArrayList" ofType="Student" select="findStudentByTeacherId" column="id"/>
</resultMap>
<select id="findStudentByTeacherId" resultType="Student">
select * from student where tid = #{tid};
</select>
</mapper>
注:
1、关联 - association 【多对一】
2、集合 - collection 【一对多】
3、javaType & ofType
- javaType用来指定实体类中属性的类型
- ofType用来指定映射到List或者集合中的pojo类型,泛型中的约束类型
评论 (0)