欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

mybatis-puls中的resultMap數(shù)據(jù)映射

 更新時間:2021年08月31日 11:28:25   作者:小屁孩~~  
這篇文章主要介紹了mybatis-puls中的resultMap數(shù)據(jù)映射,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

mybatis-puls resultMap數(shù)據(jù)映射

resultType

resultType可以把查詢結(jié)果封裝到pojo類型中,但必須pojo類的屬性名和查詢到的數(shù)據(jù)庫表的字段名一致。

如果sql查詢到的字段與pojo的屬性名不一致,則需要使用resultMap將字段名和屬性名對應(yīng)起來,進(jìn)行手動配置封裝,將結(jié)果映射到pojo中!

resultMap

resultMap可以實(shí)現(xiàn)將查詢結(jié)果映射為復(fù)雜類型的pojo,比如在查詢結(jié)果映射對象中包括pojo和list實(shí)現(xiàn)一對一查詢和一對多查詢。

  • 數(shù)據(jù)庫字段:user_id,
  • 實(shí)體類字段:userId
  • 需要手動配置設(shè)置resultMap

Mapper中基本查詢語句

<!-- 查詢所有的訂單數(shù)據(jù) -->
    <!-- resultMap:填入配置的resultMap標(biāo)簽的id值 -->
    <select id="queryOrderAll" resultMap="orderResultMap">
        SELECT id, user_id,
        number,
        createtime, note FROM `order`
    </select>

resultMap中字段映射

<!-- resultMap最終還是要將結(jié)果映射到pojo上,type就是指定映射到哪一個pojo -->
    <!-- id:設(shè)置ResultMap的id -->
    <resultMap type="order" id="orderResultMap">
        <!-- 定義主鍵 ,非常重要。如果是多個字段,則定義多個id -->
        <!-- property:主鍵在pojo中的屬性名 -->
        <!-- column:主鍵在數(shù)據(jù)庫中的列名 -->
        <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>

Mybatis ResultMap結(jié)果集映射

當(dāng)我們的POJO中的字段與數(shù)據(jù)庫中的字段不一致時,在利用resultType進(jìn)行結(jié)果集映射時,不一致的字段將會被賦值為null,這時我們可以利用ResultMap映射進(jìn)行賦值

POJO

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String password;
}

數(shù)據(jù)庫字段

在這里插入圖片描述

ResultType

<select id="getUserList" resultType="User">
    select * from user;
</select>

可以出數(shù)據(jù)庫中是pwd,而pojo中是password,這樣利用resultType是無法映射的,password查出來的結(jié)果為null

在這里插入圖片描述

ResultMap

<select id="getUserList" resultMap="UserMap">
    select * from user;
</select>
<resultMap id="UserMap" type="User">
    <result column="id" property="id"/>
    <result column="name" property="name"/>
    <result column="pwd" property="password"/>
</resultMap>

我們用resultMap替換resultType

UserMap與下面resultMap里的id屬性的值保持一致即可

type為返回值類型,這里我之所以是User是因?yàn)槲移鹆藙e名,如果沒有起別名要寫出完整的路徑

在resultMap中,column代表數(shù)據(jù)庫中的列,也就是數(shù)據(jù)庫里的字段,property為數(shù)據(jù)庫中的字段映射的結(jié)果,這里我們與pojo保持一致即可,數(shù)據(jù)庫中的pwd被映射為password,pojo里的password也就能賦值成功了

在這里插入圖片描述

以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論