第十一章、一對多
阿新 • • 發佈:2020-09-12
比如一個老師擁有多個學生
按照結果巢狀處理
1 <resultMap id="TeacherStudent" type="Teacher"> 2 <result property="id" column="tid"/> 3 <result property="name" column="tname"/> 4 <collection property="students" ofType="Student"> 5 <result property="id" column="sid"/> 6 <result property="name" column="sname"/> 7 <result property="tid" column="tid"/> 8 </collection> 9 </resultMap> 10 11 <select id="getTeacher" resultMap="TeacherStudent"> 12 select s.id sid, s.name sname,t.name tname ,t.id tid13 from teacher t,student s 14 where t.id = s.tid and t.id = #{tid} 15 </select>
按照查詢巢狀處理
1 <resultMap id="TeacherStudent2" type="Teacher"> 2 <collection property="students" column="id" javaType="ArrayList" ofType="Student" select="getStudent"> 3 4</collection> 5 </resultMap> 6 7 8 9 <select id="getTeacher2" resultMap="TeacherStudent2"> 10 select * from teacher where id = #{tid} 11 </select> 12 13 <select id="getStudent" resultType="Student"> 14 select * from student where tid = #{tid} 15 </select>
小結
-
關聯 -association [多對一]
-
集合 -collectio n【一對多】
-
javaType 用來指定實體類中屬性的型別
-
ofType 用來指定對映到list 或者集合中的pojo型別, 泛型中的約束型別
注意點
-
保證SQL的可讀性,儘量保證通俗易懂
-
注意一對多 和多對一中,屬性名和欄位名的wenti如果問題不好排查錯誤,可以使用日誌,建議使用Log4j
面試高頻:
-
-
InnoDB底層原理
-
索引
-