个人Mybatis学习笔记 一对多的关系
主要使用结果集映射
步骤:1.使用lombok
2.新建实体类teacher和student
3.建立相应的mapper接口
4.写与接口对应的mapper.xml文件
5.配置核心文件mybatis-config.xml
6.测试
学生和老师实体类
@Data
public class Student {
private int id;
private String name;
private int tid;
}
@Data
public class Teacher {
private int id;
private String name;
private List<Student> students;//一个老师对应多个学生,使用集合
}
接口
public interface TeacherMapper {
//获取指定老师以下的所有学生以及老师的所有的信息
Teacher getTeacher(@Param("tid") int id);//注意被Param注释后,使用的是tid
}
一对多的思路:
1.查询老师的信息
2.查询指定老师下学生的信息
先编写sql语句
select t.id tid,t.name tname,s.id sid,s.name sname
from student s,teacher t
where s.tid=t.id and t.id=#{tid}
然后通过sql语句来进行结果嵌套
<?xml version="1.0" encoding="GBK" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kuang.dao.TeacherMapper">
<select id="getTeacher" resultMap="TeacherStudent">
select t.id tid,t.name tname,s.id sid,s.name sname
from student s,teacher t
where s.tid=t.id and t.id=#{tid}
</select>
<resultMap id="TeacherStudent" type="Teacher">
<!--resultMap映射中,所有属性可在实现类中找到,也就是id,name,students-->
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="students" ofType="Student">
<!--students这个是一个复杂的属性,我们需要用collection来进行处理,
其中它的类型是List<E>也就是Student,其次Student对象中的属性也要进行结果映射,
name对应sname,id对应sid,tid对应tid-->
<result property="name" column="sname"/>
<result property="id" column="sid"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
</mapper>
需要注意的是
在collection结果映射中,使用的是ofType而不是javaType
因为javaType不适合用于List这种集合中的泛型属性,适用于指定属性的类型
小结
- 关联 - association 【多对一】
- 集合 - collection 【一对多】
- javaType & ofType
- JavaType用来指定实体类中的类型
- ofType用来指定映射到List或者集合中的pojo类型,泛型中的约束类型