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>