多對一&一對多
阿新 • • 發佈:2021-09-08
9、多對一處理
- 多個學生,對應一個老師
- 對於學生而言,關聯,多個學生,關聯一個老師【多對一】
- 對於老師而言,集合,一個老師,有很多學生【一對多】
測試環境搭建
1.新建實體類Teacher,Student
public class Student {
private long id;
private String name;
private long tid;
private Teacher teacher;
2.建立Mapper介面
3.建立Mapper.xml
4.在核心配置檔案中繫結Mapper介面或者檔案【方式多】
5.測試查詢是否能夠成功
按照查詢巢狀處理
<select id="getStudent" resultMap="StudentTeacher"> select * from student; </select> <resultMap id="StudentTeacher" type="Student"> <result column="id" property="id"/> <result column="name" property="name"/> <!--複雜的屬性,我們需要單獨處理 物件:association 集合:collection --> <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/> </resultMap> <select id="getTeacher" resultType="com.pireua.pojo.Teacher"> select * from teacher where id=#{id}; </select>
按照結果巢狀處理
<!-- 按照結果巢狀處理--> <select id="getStudent1" resultMap="StudentTeacher1"> select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid =t.id </select> <resultMap id="StudentTeache1r" 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多對一查詢方式:
- 子查詢
- 聯表查詢
10、一對多處理
環境搭建
public class Teacher {
private long id;
private String name;
private List<String> student;
按照結果集對映巢狀處理
<select id="getTeacher" resultMap="TeacherStudent"> select s.id sid,s.name sname,t.name tname,t.id tid from teacher t,student s where t.id=s.tid and t.id=#{tid}; </select> <resultMap id="TeacherStudent" type="Teacher"> <result property="id" column="tid"/> <result property="name" column="tname"/> <!--複雜的屬性,我們需要單獨處理物件:association集合:collection javaType指定屬性的型別 ofType指定集合中泛型的型別 --> <collection property="student" ofType="Student" > <result property="id" column="sid"/> <result property="name" column="sname"/> <result property="tid" column="tid"/> </collection> </resultMap>
小結
1.關聯 -association【多對一】
2.集合 -collection【一對多】
3.javaType & ofType
1、javaType用來指定實體類中屬性的型別
2、ofType用來指定對映到List或者集合中pojo型別,泛型中的約束型別!
注意點:
- 保證SQL的可讀性,儘量保證通俗易懂
- 注意一對多和多對一中,屬性和欄位的問題
- 如果問題不好排查,可以使用日誌,建議使用Log4j
面試高頻
- Mysql引擎
- InnoDB底層原理
- 索引
- 索引優化