mybatis学习6复杂查询之一对多的处理
生活随笔
收集整理的這篇文章主要介紹了
mybatis学习6复杂查询之一对多的处理
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
前言
接上章學(xué)習(xí),上章學(xué)習(xí)多對一的處理,今天我們學(xué)習(xí)一對多的處理
一、需要用到的數(shù)據(jù)
二、一對多是什么?
例如:一個(gè)老師擁有很多個(gè)學(xué)生。
然而老師實(shí)體類中沒有學(xué)生的屬性,只能通過一個(gè)中介tid來對應(yīng)學(xué)生,屬性名與字段名不一致,并且這個(gè)屬性是一個(gè)集合,這該如何處理呢。
二、一對多該怎么處理
<!--一對多處理,思路相當(dāng)于 子查詢 和 嵌套查詢 --><!--子查詢:按查詢處理1.查詢教師信息2.查詢教師的id,尋找對應(yīng)的學(xué)生信息--><!--嵌套查詢:按結(jié)果處理: select s.id sid,s.name sname,s.tid stid,t.id tid,t.name tname from mybatis.student s,mybatis.teacher t where s.tid=t.id and t.id = #{tid}-->復(fù)雜的屬性要單獨(dú)處理,關(guān)聯(lián):association[多對一],集合:collection[一對多]
teacher這個(gè)屬性對應(yīng)的字段是tid,但他的值是一個(gè)對象,要用javaType指定這個(gè)屬性的類型是Teacher
1.按子查詢方式處理
<select id="getTeacher" resultMap="TeacherStudent">select * from mybatis.teacher where id = #{tid}</select><resultMap id="TeacherStudent" type="Teacher"><result property="id" column="id" /><result property="name" column="name" /><!--association:關(guān)聯(lián)復(fù)雜的屬性要單獨(dú)處理 關(guān)聯(lián):association[多對一] 集合:collection[一對多]javaType:指定屬性的類型集合中的泛型信息我們用ofType獲取--><collection property="students" column="id" javaType="ArrayList" ofType="Student" select="getStudent"/></resultMap><select id="getStudent" resultType="Student">select * from mybatis.student where tid = #{tid}</select>2.按嵌套方式處理(推薦)
<select id="getTeacher2" resultMap="TeacherStudent2">select s.id sid,s.name sname,s.tid stid,t.id tid,t.name tname from mybatis.student s,mybatis.teacher t where s.tid=t.id and t.id = #{tid}</select><resultMap id="TeacherStudent2" 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="stid"></result></collection></resultMap>總結(jié)
其實(shí)看懂了很簡單,mysql熟練的人一看就已經(jīng)明白了,這兩種方法的本質(zhì)就是myqsl子查詢和嵌套查詢。弄懂了原理就不言而喻了!!!
總結(jié)
以上是生活随笔為你收集整理的mybatis学习6复杂查询之一对多的处理的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mybatis学习5复杂查询之多对一的处
- 下一篇: mybatis学习7之动态sql