11、一对多
比如:一个老师拥有多个学生!
对于老师而言,一对多的关系
1.搭建环境
实体类
@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> student;
}
按照查询嵌套处理(子查询)
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from teacher where id=#{tid};
</select>
<resultMap id="TeacherStudent2" type="Teacher">
<collection property="students" ofType="Student" select="getStudentByTeacherId" column="id">
</collection>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select * from student where tid =#{tid};
</select>
</mapper>
按照结果嵌套处理(连表查询)
<select id="getTeacher" resultMap="TeacherList">
select t.name tname,t.id tid,s.id sid,s.name sname
from teacher t,student s
where s.tid=t.id and tid=#{tid};
</select>
<resultMap id="TeacherList" type="Teacher">
<result property="id" column="tid"></result>
<result property="name" column="tname"></result>
<collection property="students" ofType="Student">
<result property="id" column="sid"></result>
<result property="name" column="sname"></result>
<result property="tid" column="tid"></result>
</collection>
</resultMap>
小结
- 关联-association【多对一】
- 集合-collection【一对多】
- javaType & ofType
- javaType用来指定实体类中属性的类型
- ofType用来指定映射到List或者集合中的pojo类型,泛型中的约束条件
注意点:
- 保定SQL的可读性,通俗易懂
- 注意一对多和多对一,属性名和字段的问题
- 如果问题不好排查错误,可以使用日志,或者Log4j
面试高频
- Mysql引擎
- InnoDB底层原理
- 索引
- 索引优化!