问题:
很多时候在处理数据库数据时候会出现定义的pojo中的属性名和我们在数据库表中定义的字段名不一致,导致数据不能正常映射,从而没有正确的数据返回,而是得到NULL值
如下:
在数据库中的字段为id、name、pwd
在定义的pojo的属性名为id、name、password
package com.cbbpp.pojo;
public class User {
private int id;
private String name;
private String password;
//getter and setter
}
解决方案:
方式一:采用起别名的方式,在对应的UserMapper.xml文件中把SQL语句改动以下如下即可
<mapper namespace="com.cbbpp.dao.UserMapper">
<!--用as别名使数据库字段和pojo属性名匹配-->
<select id="getUserById" parameterType="int" resultType="com.cbbpp.pojo.User">
select id,name,pwd as password from mybatis.user where id = #{id}
</select>
</mapper>
方式二:resultMap结果集映射
数据库字段 id name pwd
pojo属性名 id name password
<?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.cbbpp.dao.UserMapper">
<!--结果集映射-->
<resultMap id="UserMap" type="User">
<!--其中column为数据库的字段名,property为pojo对象中的属性名-->
<result column="id" property="id"></result>
<result column="name" property="name"></result>
<result column="pwd" property="password"></result>
</resultMap>
<!--根据ID查询用户-->
<select id="getUserById" parameterType="int" resultMap="UserMap">
select * from mybatis.user where id = #{id}
</select>
</mapper>
定义了一个<resultMap>标签,
<resultMap>标签的id是下面<select>标签中resultMap自定义的一个值UserMap,
这样就将<resultMap>内的结果集映射规则和<select>标签绑定在一起,
然后在<resultMap>标签内部有<result>标签,其中column为数据库的字段名,property为pojo对象中的属性名
一一列举出来,对应好就行