mybatis学习笔记4----解决在大项目中,属性名和字段名不一致的问题

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

实例程序mybatis-03包

1.起别名解决问题

就是java程序的实体类的命名如password和数据库表的字段命名如pwd不一样。

在查询时会出现返回为null,这是因为在查询过程中,找不到实体类的属性值,在数据库表的字段上,没有匹配的。

  • 解决方法

    1. 起别名

      select * from mybatis.user where id={#id}

      ​ select id ,name,pwd as password from mybatis.user where id={#id}

通过把pwd转化为password来解决。

2.resultMap结果集映射

column是数据库中的列,property是实体类的字段。

  <!--结果集映射-->
    <resultMap id="UserMap" type="com.kuang.pojo.User">
        <result column="id" property="id"></result>
        <result column="name" property="name"></result>
        <result column="pwd" property="password"></result>
    </resultMap>


    <!--这里resultType就是使用的别名-->
    <select id="getUserList" resultMap="UserMap">
    select * from mybatis.user
    </select>

通过将实体类的属性和数据库表的字段绑定,形成映射来解决不一致的问题。

这里只要一个就可以。

  1. resultMap是mybatis中最重要最强大的元素,
  2. resultMap的设计思想是,对于简单的而语句不需要配置显式的结果映射,而对于复杂的语句只需要描述他们的关系就可以了。

猜你喜欢

转载自blog.csdn.net/weixin_45263852/article/details/114413391