1、问题
数据库中的字段:
新建一个项目,拷贝之前的,测试实体类字段不一致的情况;
//实体类
public class User {
private int id;
private String name;
private String password;
测试出现问题:
select * from mybatis.user where id=#{id}相当于select id,name,pwd from mybatis.user where id=#{id}
2、解决方法一
取别名
<select id="getUserById" parameterType="int" resultType="com.beyond.pojo.User">
select id,name,pwd as password from mybatis.user where id=#{id}
</select>
3、解决方法二(resultMap结果集映射)(重点)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.beyond.dao.UserMapper">
<!--结果集映射-->
<resultMap id="UserMap" type="User">
<!--column数据库中的字段,property实体类中的属性,二者一一对应-->
<!--<result column="id" property="id"/>-->
<!--<result column="name" property="name"/>-->
<result column="pwd" property="password"/>
</resultMap>
<!--查询语句:
id:对应namespace中的方法名;
parameterType:参数类型
-->
<select id="getUserById" parameterType="int" resultMap="UserMap">
select * from mybatis.user where id=#{id}
</select>
</mapper>
resultMap
元素是MyBatis中最重要和最强大的元素。resultMap
的设计使得简单的语句根本不需要配置显式的结果映射,而对于复杂的语句只需要描述他们的关系就行了。