MyBatis結果集處理,中resultType和resultMap的區別


http://blog.csdn.net/leo3070/article/details/77899574


使用resultType

<select id="selectUsers" parameterType="int" resultType="com.someapp.model.User">
  select id, username, hashedPassword
  from some_table
  where id = #{id}
</select>

這些情況下,MyBatis 會在 幕后自動創建一個 ResultMap(其實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>


resultType可以直接返回給出的返回值類型,比如String、int、Map,等等,其中返回List也是將返回類型定義為Map,然后mybatis會自動將這些map放在一個List中,resultType還可以是一個對象-屬性名自動映射


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

外部resultMap的type屬性表示該resultMap的結果是一個什么樣的類型, esultMap節點的子節點id是用於標識該對象的id的,而result子節點則是用於標識一些簡單屬性的,其中的Column屬性表示從數據庫中查詢的屬性,Property則表示查詢出來的屬性對應的值賦給實體對象的哪個屬性。




注意:用resultType的時候,要保證結果集的列名與java對象的屬性相同,而resultMap則不用,而且resultMap可以用typeHander轉換




免責聲明!

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



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