1. 程式人生 > 實用技巧 >resultMap的用法以及關聯結果集對映

resultMap的用法以及關聯結果集對映

resultType

resultType可以把查詢結果封裝到pojo型別中,但必須pojo類的屬性名和查詢到的資料庫表的欄位名一致。
如果sql查詢到的欄位與pojo的屬性名不一致,則需要使用resultMap將欄位名和屬性名對應起來,進行手動配置封裝,將結果對映到pojo中

resultMap

resultMap可以實現將查詢結果對映為複雜型別的pojo,比如在查詢結果對映物件中包括pojo和list實現一對一查詢和一對多查詢。

先在Mapper檔案中,配置基本的sql語句

<!-- 查詢所有的訂單資料 -->
    <!-- resultMap:填入配置的resultMap標籤的id值 -->
    <select id="queryOrderAll" resultMap="orderResultMap">
        SELECT id, user_id,
        number,
        createtime, note FROM `order`
    </select>

配置resultMap標籤,對映不同的欄位和屬性名

<!-- resultMap最終還是要將結果對映到pojo上,type就是指定對映到哪一個pojo -->
    <!-- id:設定ResultMap的id -->
    <resultMap type="order" id="orderResultMap">
        <!-- 定義主鍵 ,非常重要。如果是多個欄位,則定義多個id -->
        <!-- property:主鍵在pojo中的屬性名 -->
        <!-- column:主鍵在資料庫中的列名 -->
        <id property="id" column="id" />

        <!-- 定義普通屬性 -->
        <result property="userId" column="user_id" />
        <result property="number" column="number" />
        <result property="createtime" column="createtime" />
        <result property="note" column="note" />
    </resultMap>

結果就可以封裝到pojo型別中