ResultMap结果集映射,可以解决数据库中的表字段名与实体类中的属性名不同的问题
//实体类
public class User {
int userId;
String userName;
String userPwd;
public User() {}
public User(int userId, String userName, String userPwd) {
this.userId = userId;
this.userName = userName;
this.userPwd = userPwd;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPwd() {
return userPwd;
}
public void setUserPwd(String userPwd) {
this.userPwd = userPwd;
}
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", userPwd='" + userPwd + '\'' +
'}';
}
}
<?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接口 -->
<!-- 等同于JDBC中的UserDaoImpl(接口实现类),转变为Mapper配置文件 -->
<mapper namespace="com.comprehensive.dao.UserMapper">
<!-- resultMap结果集 解决属性名和字段名不一致的问题 -->
<resultMap id="map1" type="com.comprehensive.pojo.User">
<result column="id" property="userId"></result>
<result column="name" property="userName"></result>
<result column="pwd" property="userPwd"></result>
</resultMap>
<select id="getListOfUser" resultMap="map1" resultType="com.comprehensive.pojo.User">
select * from mybatis.user
</select>
</mapper>
//测试类
public class UserMapper_Test {
@Test
//resultMap结果集 解决属性名和字段名不一致的问题
public void test() {
SqlSession sqlSession = MyBatis_Util.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
for(User user : mapper.getListOfUser()) System.out.println(user);
sqlSession.close();
}
}