8.一对多,多对一
对于数据库中存在多种关系,比如一对多、多对一或者多对多。在实体类设计中需要考虑其关系。
8.1多对一处理
回顾MySQL多对一查询方式:
- 子查询
- 联表查询
学生类:
public class Student {
private int id;
private String name;
//学生关联一个老师
private Teacher teacher;
}
老师类:
public class Teacher {
private int id;
private String name;
}
按照查询嵌套处理
MyBatis中,我们需要查询笛卡尔积结果时,直接书写以下代码将得不到正确的返回值:
<select id="getStudent" resultType="com.Z.pojo.Student">
select * from student s,teacher t where s.tid=t.id;
</select>
在resultMap设计中,单一属性选择property与column即可。
对于复杂的属性需要单独处理:
- 对象:association
- 集合:collection
student中存在一个对象teacher将会得到null
因此考虑使用resulMap 建立新的映射表。
- 查询所有学生信息
- 根据查询到的老师tid,寻找对应的老师 ----子查询
<select id="getStudent" resultMap="StudentTeacher">
select * from student;
</select>
<resultMap id="StudentTeacher" type="com.Z.pojo.Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher" column="tid" javaType="com.Z.pojo.Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="com.Z.pojo.Teacher">
select *from teacher where id = #{id}
</select>
按照结果嵌套处理
直接查询相应的结果,再将所有查询结果进行一一对应建立映射。
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid,s.name sname,t.id tid,t.name tname
from student s,teacher t
where s.tid=t.id;
</select>
<resultMap id="StudentTeacher2" type="com.Z.pojo.Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="com.Z.pojo.Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
8.2一对多处理
在此例中,一个老师对应多个学生。
学生类:
public class Student {
private int id;
private String name;
private int tid
}
老师类:
public class Teacher {
private int id;
private String name;
//一个老师对应多个学生
private List<Student> students
}
一对多查询举例:
按照结果嵌套处理
//获取指定老师下的所有信息
Teacher getTeacher(@Param(tid) int id)
<select id="getTeacher" 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;
</select>
<resultMap id="TeacherStudent" type="com.Z.pojo.Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<!--集合中的泛型信息,采用ofType获取-->
<collection property ="students" ofType="com.Z.pojo.Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
按照查询嵌套处理
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from teacher where id=#{tid}
</select>
<resultMap id="TeacherStudent2" type="com.Z.pojo.Teacher">
<!--相同部分可省略-->
<!--集合中的泛型信息,采用ofType获取-->
<collection property ="students" JavaType="ArrayList"ofType="com.Z.pojo.Student"select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="com.Z.pojo.Student">
select * from student where tid=#{tid}
</select>
小结
-
关联-association 【多对一】
-
集合-collection 【一对多】
-
javaType & ofType
javaType用来指定实体类中属性类型
ofType用来指定映射到List或者集合中的pojo类型,即泛型中的约束类型。
一般采用按照结果处理。
面试高频
- Mysql引擎
- InnoDB底层原理
- 索引
- 索引优化