1. 程式人生 > >Mybatis解決屬性名和欄位名不一致

Mybatis解決屬性名和欄位名不一致

資料庫中表的設計
這裡寫圖片描述
實體類
這裡寫圖片描述
mapper對映檔案
這裡寫圖片描述
測試
這裡寫圖片描述
結果
這裡寫圖片描述

問題:密碼沒有獲取到?

原因:mybatis會根據查詢的列名(會將列名轉為小寫)去進行設值(列名setter方法)

解決列名和屬性名不一致的方法

1 .為列名指定別名 別名和java實體類的屬性名一致

select id,name,pwd as password from User where id = #{id}

2 .設定結果對映型別

 <select id="selectUser" resultMap="UserMap">
        select id,name,pwd  from User where id = #{id}
    </select
>
<resultMap type="User" id="UserMap"> <!-- id為主鍵 --> <id column="id" property="id"></id> <!--column資料庫中表的名 property是對應類的屬性 --> <result column="name" property="name"></result> <result column="pwd" property="password"
>
</result> </resultMap>

resultType和resultMap的區別

resultType:當使用resultType做SQL語句返回結果型別處理時,對於SQL語句查詢出的欄位在相應的pojo中必須有和它相同的欄位對應,而resultType中的內容就是pojo在本專案中的位置。

resultMap:當使用resultMap做SQL語句返回結果型別處理時,通常需要在mapper.xml中定義resultMap進行pojo和相應表字段的對應。(多用於複雜的對映關係)