ssm mapper.xml講解


1.resultMap

resultMap就是結果集映射的配置標簽,

二、從SQL查詢結果到領域模型實體                  

  在深入ResultMap標簽前,我們需要了解從SQL查詢結果集到JavaBean或POJO實體的過程。

  1. 通過JDBC查詢得到ResultSet對象

  2. 遍歷ResultSet對象(結果集(ResultSet)是數據中查詢結果返回的一種對象,可以說結果集是一個存儲查詢結果的對象,但是結果集並不僅僅具有存儲的功能,他同時還具有操縱數據的功能,可能完成對數據的更新等),並將每行數據暫存到HashMap(即下文的resultmap)實例中,以結果集的字段名或字段別名為鍵,以字段值為值

  3. 根據ResultMap標簽的type屬性(返回值的全限定類名,或類型別名)通過反射實例化領域模型,(autoMapping屬性,true為:自動映射功能就是自動查找與字段名小寫同名的屬性名,並調用setter方法)

  4. 根據ResultMap標簽的type屬性和id(主鍵)、result(屬性)等標簽信息將HashMap中的鍵值對,填充到領域模型實例中並返回

舉個例子:

1.示例1:通過setter構造領域模型

public class EStudent{
  private long id;
  private String name;
  private int age;
  // getter,setter方法

  /**
   * 必須提供一個無參數的構造函數
   */
  public EStudent(){}
}

 

 <!-- 屬性id代表整個經過處理后的結果集resultMap的標識,type代表使用哪種類作為其映射的類,可以是別名或者全限定名-->
    <resultMap id="getStudentRM" type="EStudnet">
        子元素id代表resultMap的主鍵
        <id property="id" column="ID"/>
      <!--  property: 映射數據庫列的字段的java pojo類的成員變量名
        (若映射失敗,myatis會映射成搜索給定名稱的字段)
        column:數據庫的列名或者列標簽別名
        result代表其屬性。-->
        <result property="studentName" column="Name"/>
        <result property="studentAge" column="Age"/>
    </resultMap>

 示例2:通過構造函數構造領域模型

public class EStudent{
  private long id;
  private String name;
  private int age;
  // getter方法
  public EStudent(long id, String name, int age){
    this.id = id;
    this.name = name;
    this.age = age;
  }
}
<select id="getStudent" resultMap="getStudentRM">
  SELECT ID, Name, Age
    FROM TStudent
</select>
<resultMap id="getStudentRM" type="EStudnet">

<!-----
         constructor元素 ,指定使用指定參數列表的構造函數來實例化領域模型。注意:其子元素順序必須與參數列表順序對應

                                 idArg子元素 ,標記該入參為主鍵

                                 arg子元素 ,標記該入參為普通字段(主鍵使用該子元素設置也是可以的)
------->

  <constructor>
    <idArg column="ID" javaType="_long"/>
    <arg column="Name" javaType="String"/>
    <arg column="Age" javaType="_int"/>
  </constructor>
</resultMap>

轉載。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM