mybatis中resultType和resultMap使用時的區別

mybatis中select元素有兩個屬性resultType和resultMap,對於單表查詢映射或多表聯合查詢映射來說,他們都能達到要求

javaBean

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;
  }
}

使用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
-->
<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

  • 1.對應的是java對象中的屬性,大小寫不敏感,
  • 2.如果放的是java.lang.Map,key是查詢語句的列名,value是查詢的值,大小寫敏感
  • 3.resultMap:指的是定義好了的id的,是定義好的resyltType的引用
    注意:用resultType的時候,要保證結果集的列名與java對象的屬性相同,而resultMap則不用,而且resultMap可以用typeHander轉換
  • 4.type:java 對象對應的類,id:在本文件要唯一column :數據庫的列名或別名,property:對應java對象的屬性,jdbcType:java.sql.Types
    查詢語句中,resultMap屬性指向上面那個屬性的標籤的id
    parameterType:參數類型,只能傳一個參數,如果有多個參數要封裝,如封裝成一個類,要寫包名加類名,基本數據類型則可以省略
  • 5.一對1、一對多時,若有表的字段相同必須寫別名,不然查詢結果無法正常映射,出現某屬性爲空或者返回的結果與想象中的不同,而這往往是沒有報錯的。
  • 6.若有意外中的錯誤,反覆檢查以上幾點,和認真核查自己的sql語句,mapper.xml文件是否配置正確。

另外還有resultMap 元素,它是 MyBatis 中最重要最強大的元素,它能提供級聯查詢,緩存等功能


參考https://blog.csdn.net/leo3070/article/details/77899574?utm_source=copy

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章