MyBatis中resultType和resultMap的區別

一、綜述
MyBatis中在查詢進行select映射的時候,返回類型可以用resultType,也可以用resultMap,resultType是直接表示返回類型的,而resultMap則是對外部ResultMap的引用,但是resultType跟resultMap不能同時存在。
在MyBatis進行查詢映射時,其實查詢出來的每一個屬性都是放在一個對應的Map裏面的,其中鍵是屬性名,值則是其對應的值。
①當提供的返回類型屬性是resultType時,MyBatis會將Map裏面的鍵值對取出賦給resultType所指定的對象對應的屬性。所以其實MyBatis的每一個查詢映射的返回類型都是ResultMap,只是當提供的返回類型屬性是resultType的時候,MyBatis對自動的給把對應的值賦給resultType所指定對象的屬性。
②當提供的返回類型是resultMap時,因爲Map不能很好表示領域模型,就需要自己再進一步的把它轉化爲對應的對象,這常常在複雜查詢中很有作用。

二、參數傳遞

傳參方法可以@Param(“***”),其中***是參數類型,可以隨意定義,但是一定要和映射文件一致。

例如:

方法:

int getLogCount(@Param("attTime")String attTime,@Param("userId")String userId);

映射文件:

<select id="getLogCount" resultType="int">
select COUNT(*) from AttLog where attTime = #{attTime} and userId = #{userId};
</select>

也可以是一個對象,

<insert id="saveDeviceUserInfo" parameterType="com.cachee.ilabor.att.clientmodel.DeviceUserInfo">
insert into deviceUserInfo(deviceId,companyId,userId,pin,name,pri,passwd,card,grp,tz,verify)
values(#{deviceId},#{companyId},#{userId},#{pin},#{name},#{pri},#{passwd},#{card},#{grp},#{tz},#{verify});
</insert>

同樣也可以這樣獲取:#{0}、#{1}、#{2}、#{3}、、、、、、

當傳遞過來是一個數組時:

方法:void updateSendState(@Param("updateId")int[] updateId);

映射文件:

<update id="updateSendState">
update deviceUserInfo set sendState = 1 where id in 
<foreach item="item" index="index" collection="updateId" open="(" separator="," close=")">
#{item} 
</foreach>
</update>

三、resultType

resultType可以直接返回給出的返回值類型,比如String、int、Map,等等,其中返回List也是將返回類型定義爲Map,然後mybatis會自動將這些map放在一個List中,resultType還可以是一個對象,舉例如下:

返回常見類型:

  <select id="getLogCount" resultType="int">
    select COUNT(*) from AttLog where attTime = #{attTime} and userId = #{userId};
  </select>

返回Map或者List:

<select id="getDeviceInfoByDeviceId" resultType="Map">
  select userCount as usercount,
  fingerCount as fingercount,
  faceCount as facecount,
  attRecordCount as recordcount,
  lastOnline,
  state as status
  from DeviceInfo where deviceId = #{deviceId} and tb_isDelete = 0;
</select>

返回一個對象:

<select id="queryAllDeviceInfo" resultType="com.cachee.ilabor.att.clientmodel.DeviceInfo">
select * from deviceInfo where tb_isDelete = 0;
</select>

MyBatis會自動創建一個ResultMap對象,然後基於查找出來的屬性名進行鍵值對封裝,然後再看到返回類型是DeviceInfo對象,再從ResultMap中取出與DeviceInfo對象對應的鍵值對進行賦值。

四、resultMap

當返回類型直接是一個ResultMap的時候也是非常有用的,這主要用在進行復雜聯合查詢上,因爲進行簡單查詢是沒有什麼必要的。先看看一個返回類型爲ResultMap的簡單查詢,再看看複雜查詢的用法。

<resultMap id="BaseResultMap" type="com.cachee.ilabor.att.clientmodel.User"> 
<result column="ID" property="id" jdbcType="INTEGER" /> 
<result column="SN" property="SN" jdbcType="VARCHAR" /> 
<result column="companyId" property="companyId" jdbcType="VARCHAR" /> 
<result column="tb_isDelete" property="tb_isDelete" jdbcType="VARCHAR" />
<result column="tb_createTime" property="tb_createTime" jdbcType="VARCHAR" /> 
</resultMap>

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