Mybatis-解决属性名和字段名不一致的问题
解决属性名和字段名不一致的问题
1. 问题
在数据库中,密码字段为pwd,而在实体类中为password
package com.wang.pojo;
public class User {
private int id;
private String name;
private String password;
public User(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
public User() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}
测试出现问题
package com.wang.dao;
import com.wang.pojo.User;
import com.wang.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserMapperTest {
//
@Test
public void testGetUserById() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
sqlSession.close();
}
}
User{id=1, name='张三', password='null'}
select * from mybatis.user where id = #{id};
等同于
select id, name, pwd from mybatis.user where id = #{id};
MyBatis 在设置预处理语句(PreparedStatement)中的参数或从结果集中取出一个值时, 都会用类型处理器将获取到的值以合适的方式转换成 Java 类型。
经过类型处理器处理后,此时,在实体类中找不到pwd的字段
.解决方法:
- 起别名: pwd as 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.wang.dao.UserMapper">
<select id="getUserById" parameterType="int" resultType="User">
select id, name, pwd as password from mybatis.user where id = #{id};
</select>
</mapper>
2. ResultMap
结果集映射
数据库 id name pwd
实体类 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.wang.dao.UserMapper">
<!--使用resultMap时,此处不要指定resultType,在下面写resultMap时再指定其type属性-->
<select id="getUserById" parameterType="int" resultMap="UserMap">
select * from mybatis.user where id = #{id};
</select>
<!--结果集映射 resultMap id = 找到要映射的标签(在上面的resultMap中设定的标签)-->
<resultMap id="UserMap" type="User">
<!--column 数据库中的字段; property 实体类中的属性-->
<result column="pwd" property="password"/>
</resultMap>
</mapper>