【3】resultMap结果集映射

5、解决属性名和字段名不一致的问题

1.具体例子

pojo实体类:

public class User {
    
    

    private Integer uid;
    private String username;
    private String pwd;
}

数据库相应字段:

在这里插入图片描述

测试类输出结果:

    @Test
    public void getUserByID(){
    
    
        SqlSession sqlSession;
        try {
    
    
            sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            User user = mapper.getUserByID(2);
            System.out.println(user);
        }finally {
    
    
            MybatisUtils.closeSqlSession();
        }
    }

在这里插入图片描述

字段未对齐出现这种情况。

2、解决方法

1、起别名

    <select id="getUserByID" parameterType="int" resultMap="UserMap">
        select uid,username,password as pwd from users where uid = #{id}
    </select>

2、resultMap

结果集映射

uid  username  pwd
uid  username  password
    <!--结果集映射-->
    <resultMap id="UserMap" type="User">
        <!--colunm数据库中的字段,properties实体类中的属性-->
        <result column="uid" property="id"/>
        <result column="username" property="name"/>
        <result column="password" property="pwd"/>
    </resultMap>
    <select id="getUserByID" parameterType="int" resultMap="UserMap">
        select * from users where uid = #{id}
    </select>
  • resultMap 元素是 MyBatis 中最重要最强大的元素。
  • ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
  • ResultMap 最优秀的地方在于,虽然你已经对它相当了解了,但是根本就不需要显式地用到他们。

猜你喜欢

转载自blog.csdn.net/weixin_43215322/article/details/109546311