Mybatis应用resultMap(结果集映射)解决属性名和字段名不一致的问题

2022-06-22 08:35:37

1、问题说明

  • 数据库中的字段

  • 测试实体类属性名与字段名不一致的情况

    publicclassUser{privateint id;privateString name;privateString password;
  • 测试出现问题

    //select * from mybatisnote.user where id = #{id}
    //类型处理器
    //select id,name, pwd from mybatisnote.user where id = #{id}
  • 简单解决问题的方法:

    • 起别名

      <selectid="getUserById"parameterType="int"resultType="com.ping.pojo.User">
          select id,name,pwd as password from mybatisnote.user where id = #{id};</select>

2、resultMap结果集映射

<!--结果集映射--><resultMapid="UserMap"type="User"><!--column数据库中的字段,property实体类中的属性--><!-- <result column="id" property="id"/>
        <result column="name" property="name"/>--><resultcolumn="pwd"property="password"/></resultMap><selectid="getUserById"parameterType="int"resultMap="UserMap">
    select * from mybatisnote.user where id = #{id};</select>
  • resultMap元素是MyBatis中最重要最强大的元素
  • ResultMap的设计思想是,对于简单的语句根本不需要配置显式的结果映射,而对于复杂一点的语句只需要描述它们的关系就行了
  • ResultMap最优秀的地方在于,虽然你已经对它相当了解了,但是根本就不需要显式地用到他们
  • 作者:玖玖拾月陆
  • 原文链接:https://blog.csdn.net/qq_45974648/article/details/120225874
    更新时间:2022-06-22 08:35:37