Mybatis的多对一
一、对应关系
- 多个学生,对应一个老师。
- 对于学生这边而言, 关联: 多个学生关联一个老师。
- 对于老师而言,集合: 一个老师有很多学生。
二、测试环境的搭建
- 导入lombok。
- 新建实体类Student,Teacher。
1 2 3 4 5 6 7 8 9
| @Data @NoArgsConstructor public class Student { private int id; private String name; private Teacher teacher;
}
|
1 2 3 4 5 6 7
| @Data @NoArgsConstructor public class Teacher { private int id; private String name; }
|
- 建立Mapper接口。
- 建立Mapper.xml文件。
1 2 3 4 5 6 7 8
| <?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.nichu.dao.TeacherMapper">
</mapper>
|
- 在核心配置文件中绑定Mapper接口或者文件!
- 测试查询是否能够成功。
三、按照查询嵌套的方式实现多对一
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
<select id="getStudent" resultType="Student" resultMap="StudentTeacher"> select * from students; </select>
<resultMap id="StudentTeacher" type="Student"> <result property="id" column="id"/> <result property="name" column="name"/>
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/> </resultMap>
<select id="getTeacher" resultType="Teacher"> select * from mybatis.teacher where id =#{id} </select>
|
四、按照结果嵌套处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
<select id="getStudent2" resultMap="StudentTeacher2"> select s.id sid ,s.name sname,t.name tname from students s,teacher t where s.tid = t.id; </select> <resultMap id="StudentTeacher2" type="Student"> <result property="id" column="sid"/> <result property="name" column="sname"/> <association property="teacher" javaType="Teacher"> <result property="name" column="tname"/> </association> </resultMap>
|
五、回顾MySQL多对一查询方式
1. 子查询
1
| select * from students where tid = (select id from teacher)
|
2. 联表查询
1
| select * from students s,teacher t where s.tid = t.id;
|
-------------本文结束感谢您的阅读-------------