【Mybatis系列】ResultMap結果集對映
阿新 • • 發佈:2021-01-10
ResultMap結果集是用來定義SQL查詢結果與java物件對映關係,當欄位名和屬性名不一致的時候,可以使用resultMap,resultType跟resultMap不能同時存在。
實體類的欄位如下:
public class User {
private int id;
private String name;
private String password;
}
而資料庫中的欄位如下:
顯然這個資料庫pwd欄位和java實體類中的password欄位不一樣。 執行結果,password=‘null’:User{id=1, name='jason', password='null'}
其實SQL實現原理如下:
select * from mybatis.user where id = #{id}
型別處理器
select id,name,pwd from mybatis.user where id = #{id}
解決辦法:
方法一:起別名<select id="getUserById" resultType="User"> select pwd as password from mybatis.user where id=#{id} </select>
方法二:resultMap結果集對映
- resultMap 元素是 MyBatis 中最重要最強大的元素。它可以讓你從 90% 的 JDBC ResultSets 資料提取程式碼中解放出來。
- 實際上,在為一些比如連線的複雜語句編寫對映程式碼的時候,一份 resultMap 能夠代替實現同等功能的長達數千行的程式碼。
- ResultMap 的設計思想是,對於簡單的語句根本不需要配置顯式的結果對映,而對於複雜一點的語句只需要描述它們的關係就行了。
<!--結果集對映--> <resultMap id="UserMap" type="User"> <!--column資料庫中的欄位 property實體類中的屬性--> <result column="id" property="id"/> <result column="name" property="name"/> <result column="pwd" property="password"/> </resultMap> <select id="getUserById" resultMap="UserMap"> select * from mybatis.user where id=#{id} </select>