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>

 

参考链接:

http://blog.csdn.net/woshixuye/article/details/27521071

http://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html#Result_Maps

猜你喜欢

转载自blog.csdn.net/yj108283/article/details/80179325