MyBatis查詢時屬性名和欄位名不一致問題的解決方法
阿新 • • 發佈:2021-01-19
問題
當我們資料庫中的欄位和實體類中的欄位不一致的時候,查詢會出問題
資料庫欄位是 pwd
id name pwd 1 張三 123456 2 李四 123456 3 王五 123456 4 趙六 123456
實體類欄位是 password
public class User { private int id; private String name; private String password; }
查出來結果發現, password 是 null
User{id=1,name='張三',password='null'} User{id=2,name='李四',password='null'} User{id=3,name='王五',password='null'} User{id=4,name='趙六',password='null'}
原因是型別處理器
select * from user // 型別處理器:我們查詢 select * 實際是查詢 select id,name,pwd select id,pwd from user
解決辦法
- resultMap:結果集對映
- sql起別名
select id,pwd as password from user
解決方案:resultMap
結果集對映:https://mybatis.org/mybatis-3/zh/sqlmap-xml.html#Result_Maps
- resultMap 元素是 MyBatis 中最重要最強大的元素
- ResultMap 的設計思想是,對簡單的語句做到零配置,對於複雜一點的語句,只需要描述語句之間的關係就行了
我們只需要在Mapper.xml 中加入結果集對映即可,且只加需要對映的欄位即可
<mapper namespace="com.pro.dao.UserMapper"> <!--id: 下面select語句中resultMap繫結的(識別符號/名稱),type: 我們的實體類--> <resultMap id="UserMap" type="User"> <!--column: 對應資料庫中的欄位,property: 對應實體類中的屬性--> <result column="pwd" property="password"/> </resultMap> <select id="getUserList" resultMap="UserMap"> select * from users </select> </mapper>
總結
到此這篇關於MyBatis查詢時屬性名和欄位名不一致問題解決的文章就介紹到這了,更多相關MyBatis查詢時屬性名和欄位名不一致內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!