【Mybatis系列】ResultMap结果集映射

ResultMap结果集是用来定义SQL查询结果与java对象映射关系,当字段名和属性名不一致的时候,可以使用resultMap,resultType跟resultMap不能同时存在。
 
实体类的字段如下:
public class User {
  private int id;
  private String name;
  private String password;
}

而数据库中的字段如下:

 
显然这个数据库pwd字段和java实体类中的password字段不一样。
 
运行结果,password=‘null’:
User{id=1, name='jason', password='null'}

其实SQL实现原理如下:

select * from mybatis.user where id = #{id}

类型处理器

select id,name,pwd from mybatis.user where id = #{id}

解决办法:

 
方法一:起别名
<select id="getUserById" resultType="User">
  select pwd as password from mybatis.user where id=#{id}
</select>

方法二:resultMap结果集映射

  • resultMap 元素是 MyBatis 中最重要最强大的元素。它可以让你从 90% 的 JDBC ResultSets 数据提取代码中解放出来。
  • 实际上,在为一些比如连接的复杂语句编写映射代码的时候,一份 resultMap 能够代替实现同等功能的长达数千行的代码。
  • ResultMap 的设计思想是,对于简单的语句根本不需要配置显式的结果映射,而对于复杂一点的语句只需要描述它们的关系就行了。
<!--结果集映射-->
  <resultMap id="UserMap" type="User">
      <!--column数据库中的字段 property实体类中的属性-->
      <result column="id" property="id"/>
      <result column="name" property="name"/>
      <result column="pwd" property="password"/>
  </resultMap>

 <select id="getUserById" resultMap="UserMap">
    select * from mybatis.user where id=#{id}
 </select>

 

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

技术蜗牛-阿春

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

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

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

打赏作者

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

抵扣说明:

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

余额充值