mybatis中select元素有兩個屬性resultType和resultMap,工作中總是使用到他們,但是他們有什么區別呢?
對於單表查詢映射或多表聯合查詢映射來說,他們都能達到要求,例如
public class User { private int id; private String username; private String hashedPassword; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getHashedPassword() { return hashedPassword; } public void setHashedPassword(String hashedPassword) { this.hashedPassword = hashedPassword; } }
<select id="selectUsers" parameterType="int" resultType="com.someapp.model.User"> select id, username, hashedPassword from some_table where id = #{id} </select>
這些情況下,MyBatis 會在幕后自動創建一個 ResultMap,基於屬性名來映射列到 JavaBean 的屬性上。
如果列名沒有精確匹配,你可以在列名上使用 select 字句的別名(一個 基本的 SQL 特性)來匹配標簽。比如:
<select id="selectUsers" parameterType="int" resultType="User"> select user_id as "id", user_name as "userName", hashed_password as "hashedPassword" from some_table where id = #{id} </select>
二、使用resultMap
<resultMap id="userResultMap" type="User"> <id property="id" column="user_id" /> <result property="username" column="username"/> <result property="password" column="password"/> </resultMap> <select id="selectUsers" parameterType="int" resultMap="userResultMap"> select user_id, user_name, hashed_password from some_table where id = #{id} </select>
看出來了吧,resultType和resultMap都映射到了User對象中
三、區別
說說不同點吧,resultType 和restltMap
restulyType:
1.對應的是java對象中的屬性,大小寫不敏感,
2.如果放的是java.lang.Map,key是查詢語句的列名,value是查詢的值,大小寫敏感
3.resultMap:指的是定義好了的id的,是定義好的resyltType的引用
注意:用resultType的時候,要保證結果集的列名與java對象的屬性相同,而resultMap則不用,而且resultMap可以用typeHander轉換
4.type:java 對象對應的類,id:在本文件要唯一column :數據庫的列名或別名,protery:對應java對象的屬性,jdbcType:java.sql.Types
查詢語句中,resultMap屬性指向上面那個屬性的標簽的id
parameterType:參數類型,只能對應一個參數,如果有多個參數要封裝,如封裝成一個類,要寫包名加類名,基本數據類型則可以省略
5.一對一、一對多時,若有表的字段相同必須寫別名,不然查詢結果無法正常映射,出現某屬性為空或者返回的結果與想象中的不同,而這往往是沒有報錯的。
6.若有意外中的錯誤,反復檢查以上幾點,和認真核查自己的sql語句,mapper.xml文件是否配置正確。
另外還有resultMap 元素,它是 MyBatis 中最重要最強大的元素,它能提供級聯查詢,緩存等功能