【MyBatis】resultMap和resultType的区别

5 篇文章 2 订阅

mybatis中resultMap和resultType的区别

mybatis中在查询进行select映射的时候,返回类型可以用resultType,也可以用resultMap。resultType是直接表示返回类型的,而resultMap则是对外部ResultMap的引用,但是resultType跟resultMap不能同时存在。

public class User {

  private int id;

  private String username;

  private String hashedPassword;

//省略setter/getter方法 

}

  1. 使用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 字句的别名来匹配标签。

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

  1. 不同
  1. resultType对应的是java对象中的属性,大小写不敏感;resultMap对应的是对已经定义好了id的resultTupe的引用,key是查询语句的列名,value是查询的值,大小写敏感;
  2. 使用resultType的时候,要保证结果集的列名与java对象的属性相同,而resultMap则不用。
  3. 另外,resultMap 元素,它是 MyBatis 中最重要最强大的元素,它能提供级联查询,缓存等功能。
  • 14
    点赞
  • 58
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SunAlwaysOnline

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值