1. 程式人生 > 其它 >mybaits的一對多,多對一實現

mybaits的一對多,多對一實現

多對一

  一個老師有5個學生【集合】

  5個學生關聯一個老師【關聯】 多對一的時候resultMap裡面不用result去一一對應查詢sql的表列和實體類屬性名稱了。多的那一項要用 association【可以理解為一個物件】

    

       

    方法一:通過子查詢的方法來

    思路:先查Student資訊,根據查出來Student的tid 子查詢查詢Teacher資料

  

    <select id="getTeacherList" resultType="teacher">
        select * from mybaits.teacher where id=#{id}
    
</select> <select id="getStudentList" resultMap="studentlist"> select * from mybaits.student </select> <resultMap id="studentlist" type="student"> <result property="id" column="id"/> <result property="name" column="name"/> <
association property="teacher" column="tid" javaType="teacher" select="getTeacherList"/> </resultMap>

    方法二:關聯查詢

    <!--巢狀查詢,先查a表資料再把b表的資料直接association再使用result將屬性值和查詢出的b表資料-->
    <select id="getStudentList1" resultMap="studentlist1">
        select  a.id sid,a.name sname ,b.name tname
        from  mybaits.student a,  mybaits.teacher b
        where a.tid=b.id
    
</select> <resultMap id="studentlist1" type="student"> <result property="id" column="sid"/> <result property="name" column="sname"/> <association property="teacher" javaType="teacher"><!--這裡可以理解為【多對一】【一】代表的是一個物件,javaType是物件的類 -->
        <!--因為這裡沒有管teacher的id,所以查詢結果id都是預設值0-->
<result property="name" column="tname"/> </association> </resultMap>

一對多:

  一對多用:collection

  一對多可以理解為一個物件,一個列表

  

  

  總結:

    多對一:關聯 association

    一對多:集合 collection

    javaType:用於指定實體類中屬性的型別

    ofType:用於指定對映到集合或者list中的pojo實體型別 泛型中的約束型別