一对多的理解:
- 一个老师拥有多个学生
- 如果对于老师这边,就是一个一对多的现象,即从一个老师下面拥有一群学生(集合)!
1、实体类编写
package com.study.pojo;
public class Student {
private int id;
private String name;
private int tid;
}
package com.study.pojo;
import java.util.List;
public class Teacher {
private int id;
private String name;
private List<Student> students;
}
2、按结果嵌套处理
-
TeacherMapper接口编写方法
//获取指定老师,及老师下的所有学生 public Teacher getTeacher(int id);
-
编写接口对应的Mapper配置文件
<?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"> <mapper namespace="com.study.mapper.TeacherMapper"> <select id="getTeacherById" resultMap="TeacherStudent"> select s.tid tid,t.name tname,s.id sid,s.name sname from student s,teacher t where tid = #{id} </select> <resultMap id="TeacherStudent" type="Teacher"> <result property="id" column="tid"/> <result property="name" column="tname"/> <collection property="students" ofType="Student"> <result property="id" column="sid"/> <result property="name" column="sname"/> <result property="tid" column="tid"/> </collection> </resultMap> </mapper>
-
将Mapper文件注册到MyBatis-config文件中
<mappers> <mapper class="com.study.mapper.TeacherMapper"/> <mapper class="com.study.mapper.StudentMapper"/> </mappers>
-
测试
@Test public void getTeacherById(){ SqlSession sqlSession = mybatisUtils.getSqlSession(); TeacherMapper teacherMapper = sqlSession.getMapper(TeacherMapper.class); Teacher teacher = teacherMapper.getTeacherById(1); System.out.println(teacher); sqlSession.close(); }
3、按查询嵌套处理
-
TeacherMapper接口编写方法
public Teacher getTeacher2(int id);
-
编写接口对应的Mapper配置文件
<?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"> <mapper namespace="com.study.mapper.TeacherMapper"> <select id="getTeacherById2" resultMap="TeacherStudent2"> select id,name from teacher where id = #{id} </select> <resultMap id="TeacherStudent2" type="Teacher"> <result property="id" column="id"/> <result property="name" column="name"/> <collection property="students" column="id" javaType="ArrayList" ofType="Student" select="getStudentListByTeacherId"/> </resultMap> <select id="getStudentListByTeacherId" resultType="Student"> select * from student where tid = #{id} </select> </mapper>
-
将Mapper文件注册到MyBatis-config文件中
-
测试
@Test public void getTeacherById2(){ SqlSession sqlSession = mybatisUtils.getSqlSession(); TeacherMapper teacherMapper = sqlSession.getMapper(TeacherMapper.class); Teacher teacher = teacherMapper.getTeacherById2(1); System.out.println(teacher); sqlSession.close(); }
9.4、小结
- 关联-association
- 集合-collection
- 所以association是用于一对一和多对一,而collection是用于一对多的关系
- JavaType和ofType都是用来指定对象类型的
- JavaType是用来指定pojo中属性的类型
- ofType指定的是映射到list集合属性中pojo的类型。
注意说明:
- 保证SQL的可读性,尽量通俗易懂
- 根据实际要求,尽量编写性能更高的SQL语句
- 注意属性名和字段不一致的问题
- 注意一对多和多对一 中:字段和属性对应的问题
- 尽量使用Log4j,通过日志来查看自己的错误
【狂神说Java】Mybatis最新完整教程IDEA版通俗易懂