十六、ResultMap初体验
当我们的数据库字段和实体类字段没有保持一直时,会发生查询到某些字段为空的情况。
这时,就要用到ResultMap了。
Demo:
1. User表
2. User.java
package org.zx.pojo;
public class User {
private long id;
private String name;
private String password;
public User() {
}
public User(long id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
public long getId() {
return id;
}
public void setId(long 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 + '\'' +
'}';
}
}
3. UserMapper.java
public interface UserMapper {
public User getById(Integer id);
}
4. UserMapper.xml
<?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">
<mapper namespace="org.zx.mapper.UserMapper">
<!--id与select中的resultMap属性保持一致-->
<!--type是指将结果集映射的类型-->
<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>
<select id="getById" parameterType="int" resultMap="User">
select * from `user` where id = #{id};
</select>
</mapper>
5. 测试类:UserTest.java
public class UserTest {
@Test
public void getById(){
SqlSession sqlSession = MyBaitsUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getById(1);
System.out.println(user);
sqlSession.close();
}
}