1. 程式人生 > >resultType和resultMap的區別

resultType和resultMap的區別

mybatis中resultType和resultMap使用時的區別
mybatis中select元素有兩個屬性resultType和resultMap,工作中總是使用到他們,但是他們有什麼區別呢? 就我的使用經驗來說,對於單表查詢對映或多表聯合查詢對映來說,他們都能達到要求,例如 package com.someapp.model; 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;   } } <!– In mybatis-config.xml file –> <typeAlias type=”com.someapp.model.User” alias=”User”/> 使用resultType <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.一對1、一對多時,若有表的欄位相同必須寫別名,不然查詢結果無法正常對映,出現某屬性為空或者返回的結果與想象中的不同,而這往往是沒有報錯的。 6.若有意外中的錯誤,反覆檢查以上幾點,和認真核查自己的sql語句,mapper.xml檔案是否配置正確。 另外還有resultMap 元素,它是 MyBatis 中最重要最強大的元素,它能提供級聯查詢,快取等功能