MyBatis
11、一对多处理
- 比如:一个老师拥有多个学生!
对于老师而言,就是一对多的关系!
11.1、环境搭建同多对一
-
实体类
-
public class Student { private int studentId; private String studentName; private int teacherId; }
-
public class Teacher { private Integer teacherId; private String teacherName; //一个老师有多个学生 private List<Student> students; }
-
11.2、按照查询嵌套处理
-
<select id="getTeacherById2" resultMap="TeacherStudent2"> select * from teacher where teacher_id=#{teacher_id} </select> <resultMap id="TeacherStudent2" type="Teacher"> <result property="teacherId" column="teacher_id"></result> <result property="teacherName" column="teacher_name"></result> <collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacher" column="teacher_id"></collection> </resultMap> <select id="getStudentByTeacher" resultType="Student"> select * from student where teacher_id=#{teacher_id} </select>
11.3、按照结果嵌套处理
-
<!--按照结果嵌套处理--> <select id="getTeacherById" resultMap="TeacherStudent"> select t.teacher_id tid, t.teacher_name tname, s.student_id sid,s.student_NAME sname from student s,teacher t where s.teacher_id=t.teacher_id and t.teacher_id=#{teacher_id} </select> <resultMap id="TeacherStudent" type="Teacher"> <result property="teacherId" column="tid"></result> <result property="teacherName" column="tname"></result> <!--复杂的属性,我们需要单独处理对象:association 集合:collection javaType="" 指定属性的类型! 集合中的泛型信息,我们使用ofType获取--> <collection property="students" ofType="Student"> <result property="studentId" column="sid" ></result> <result property="studentName" column="sname" ></result> <result property="teacherId" column="tid" ></result> </collection> </resultMap>
11.4、小结
- 关联-association 多对一
- 集合-collection 一对多
- javaType && ofType
- JavaType 用来指定实体类中属性的类型。
- ofType 用来指定映射到List或者集合中的pojo类型,泛型中的约束类型!
11.5、注意点
- 保证SQL的可读性,尽量保证通俗易懂。
- 注意一对多和多对一中,属性名和字段的问题!
- 如果问题不好排查错误,可以使用日志,建议使用Log4j。
- 注意慢SQL。
11.6、面试高频
- Mysql引擎。
- InnoDB底层原理。
- 索引。
- 索引优化。
原文地址:https://www.cnblogs.com/jcooling-hai/p/15646442.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。