目录
问题:属性名和字段名不一致
参阅MyBatis实现增删改查新建一个项目来测试

public class User {
private int id; //id
private String name; //姓名
private String password; //密码和数据库不一样!
//构造
//set/get
//toString()
}//根据id查询用户
User selectUserById(int id);<select id="selectUserById" resultType="user">
select * from user where id = #{id}
</select>@Test
public void testSelectUserById() {
SqlSession session = MybatisUtils.getSession(); //获取SqlSession连接
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.selectUserById(1);
System.out.println(user);
session.close();
}测试结果:

查询出来发现 password 为空 . 说明出现了问题!
分析:
为列名指定别名 , 别名和java实体类的属性名一致 .
<select id="selectUserById" resultType="User">
select id , name , pwd as password from user where id = #{id}
</select>测试结果:

使用结果集映射->ResultMap
<resultMap id="UserMap" type="User">
<!-- id为主键 -->
<id column="id" property="id"/>
<!-- column是数据库表的列名 , property是对应实体类的属性名 -->
<result column="name" property="name"/>
<result column="pwd" property="password"/>
</resultMap>
<select id="selectUserById" resultMap="UserMap">
select id , name , pwd from user where id = #{id}
</select>测试结果:
两种方式还是稍有差别的。

resultMap 元素是 MyBatis 中最重要最强大的元素。它可以让你从 90% 的 JDBC ResultSets 数据提取代码中解放出来。resultMap 能够代替实现同等功能的长达数千行的代码。刚才的就是简单的映射语句的示例,但并没有显式指定 resultMap。比如:
<select id="selectUserById" resultType="map">
select id , name , pwd
from user
where id = #{id}
</select>上述语句只是简单地将所有的列映射到 HashMap 的键上,这由 resultType 属性指定。虽然在大部分情况下都够用,但是 HashMap 不是一个很好的模型。你的程序更可能会使用 JavaBean 或 POJO(Plain Old Java Objects,普通老式 Java 对象)作为模型。
ResultMap 最优秀的地方在于,虽然你已经对它相当了解了,但是根本就不需要显式地用到他们。
<select id="selectUserById" resultMap="UserMap">
select id , name , pwd from user where id = #{id}
</select><resultMap id="UserMap" type="User">
<!-- id为主键 -->
<id column="id" property="id"/>
<!-- column是数据库表的列名 , property是对应实体类的属性名 -->
<result column="name" property="name"/>
<result column="pwd" property="password"/>
</resultMap>如果每一次都能够这么简单可太好了。但是肯定不是的,数据库中,存在一对多,多对一的情况,之后会使用到一些高级的结果集映射,association,collection这些。