0
点赞
收藏
分享

微信扫一扫

MyBatis学习笔记--04--解决属性名与对象名不一致的问题

中间件小哥 2022-01-16 阅读 46
java

5、解决属性名与对象名不一致的问题

5.1、问题

数据库中的字段
在这里插入图片描述
新建一个项目,拷贝之前的,测试实体类字段不一致的情况

public class User {

    private int id;
    private String name;
    private String password;
}

测试出现问题
在这里插入图片描述

//select * from mybatis.user where id = #{id}
//类型处理器
//select id,name,pwd from mybatis.user where id = #{id}

解决方法:

  • 起别名

    <select id="getUserById" parameterType="int" resultType="com.seig.pojo.User">
        select id, `name`,pwd as password from mybatis.user where id = #{id}
    </select>
    

5.2、resultMap 结果集映射

<!--结果集映射-->
<resultMap id="UserMap" type="User">
    <!--column数据库中的字段,property实体类中的属性-->
<!--        <result column="id" property="id"/>-->
<!--        <result column="name" property="name"/>-->
    <result column="pwd" property="password"/>
</resultMap>

<select id="getUserById" resultMap="UserMap">
    select * from mybatis.user where id = #{id}
</select>

只需要映射需要映射的对象即可

  • resultMap 元素是 MyBatis 中最重要最强大的元素。
  • ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
  • ResultMap 的优秀之处——你完全可以不用显式地配置它们。
举报

相关推荐

0 条评论