ResultMap结果集映射,可以解决数据库中的表字段名与实体类中的属性名不同的问题

    1. //实体类
    2. public class User {
    3. int userId;
    4. String userName;
    5. String userPwd;
    6. public User() {}
    7. public User(int userId, String userName, String userPwd) {
    8. this.userId = userId;
    9. this.userName = userName;
    10. this.userPwd = userPwd;
    11. }
    12. public int getUserId() {
    13. return userId;
    14. }
    15. public void setUserId(int userId) {
    16. this.userId = userId;
    17. }
    18. public String getUserName() {
    19. return userName;
    20. }
    21. public void setUserName(String userName) {
    22. this.userName = userName;
    23. }
    24. public String getUserPwd() {
    25. return userPwd;
    26. }
    27. public void setUserPwd(String userPwd) {
    28. this.userPwd = userPwd;
    29. }
    30. @Override
    31. public String toString() {
    32. return "User{" +
    33. "userId=" + userId +
    34. ", userName='" + userName + '\'' +
    35. ", userPwd='" + userPwd + '\'' +
    36. '}';
    37. }
    38. }
    <?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();
        }
    }