一對一查詢(9)

前記:這是很早之前自學學習myBatis時的筆記,內容比較基礎,適合新手,內容基本是來自網絡,如有雷同,敬請諒解!  

      一對一查詢

     用resultType實現

                     使用resultType,定義訂單信息po類,此po類中包括了訂單信息和用戶信息

                    思路:定義專門的pojo類作爲輸出類型,其中定義了sql查詢結果集所有的字段。此方法較爲簡單,企業中使用普遍。

                    resultMap可以實現延遲加載,resultType無法實現延遲加載。

      示例:

<selectid="findOrdersList"  

        resultType="cn.po.OrdersCustom">

    SELECT

    orders.*,

    user.username,

    user.address

    FROM

    orders,    user

    WHERE orders.user_id = user.id

</select>

   用resultMap實現

                     使用resultMap,定義專門的resultMap用於映射一對一查詢結果。

                      resultMap:需要單獨定義resultMap,實現有點麻煩,如果對查詢結果有特殊的要求,使用resultMap可以完成將關聯查詢映射pojo的屬性中。

                     resultMap可以實現延遲加載,resultType無法實現延遲加載。

   示例:

               使用resultMap將查詢結果中的訂單信息映射到Orders對象中,在orders類中添加User屬性,將關聯查詢出來的用戶信息映射到orders對象中的user屬性中。

需要關聯查詢映射的是用戶信息,使用association將用戶信息映射到訂單對象的用戶屬性中。

<resultMaptype="cn.po.Orders"id="userordermap">

<!-- 這裏的id,是mybatis在進行一對一查詢時將user字段

      映射爲user對象時要使用,必須寫

-->

     <idproperty="id"column="id"/>

     <resultproperty="user_id"column="user_id"/>

     <resultproperty="number"column="number"/>

     <associationproperty="user"javaType="cn..po.User">

            <!-- 這裏的iduserid,如果寫上表示給userid屬性賦值 -->

            <id property="id"column="user_id"/>

            <result property="username"column="username"/>

            <result property="address"column="address"/>

     </association>

</resultMap>

association表示進行關聯查詢單條記錄

property表示關聯查詢的結果存儲在cn.itcast.mybatis.po.Ordersuser屬性中

javaType表示關聯查詢的結果類型

<idproperty="id"column="user_id"/>查詢結果的user_id列對應關聯對象的id屬性,這裏是<id />表示user_id是關聯查詢對象的唯一標識。

<resultproperty="username"column="username"/>查詢結果的username列對應關聯對象的username屬性。

<selectid="findOrdersListResultMap"resultMap="userordermap">

    SELECT

    orders.*,

    user.username,

    user.address

    FROM

    orders,    user

    WHERE orders.user_id = user.id

    </select>

這裏resultMap指定上面定義的resultMap,即userordermap




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章