首页 > 其他 > 详细

MyBatis(5)——解决属性名与列名不一致的问题

时间:2020-02-16 15:43:03      阅读:63      评论:0      收藏:0      [点我收藏+]

解决属性名与列名不一致的问题

  • 问题描述: 当实体类的属性与数据库的列名不对应时取不到该列数据

  • 说明:MyBatis会根据查询的列名设值(列名的setter方法),然后以此列名为做查询等操作,在此过程中将列名转化为小写。

设:数据库列名与实体类的属性名不一致,如数据库password,实体类为pwd

解决方法如下:

  1. 为列名指定别名,例如:

    select username,password pwd from users where id = #{id}
  2. 设置结果集映射,例如:

    //------------映射文件------------//
    
    <mapper namespace="cn.aaa.entity.UserMapper">
    <!-- sql映射语句 -->
      <!-- 结果映射集合 -->
      <resultMap type="User" id="UserMap">
        <!-- id是主键 -->
        <id column="id" property="id" />
        <!-- column是数据库中表的列名,property是对应实体类的属性名 -->
        <result column="username" property="username" />
        <result column="password" property="pwd"/>
      </resultMap>
    
      <!--查询语句 -->
      <!-- 因为字段名不一致,此处的resultType换成结果集映射resultMap -->
      <select id="selectAll" resultMap="UserMap">
      select * from users
      </select>
    
    
    
      <!-- 条件查询语句 -->
      <select id="selectUser" resultMap="UserMap">
      select * from users where id = #{id}
      </select>
    
      <!-- 插入语句 -->
      <!-- 会去获取到对应的实体类的getter方法 -->
      <insert id="insertUser" parameterType="User" useGeneratedKeys="true">
      insert into users(username,password) values(#{username},#{pwd})
      </insert>
    
      <!-- 更新语句 -->
      <update id="updateUser" parameterType="User">
      update users set nickname=#{nickname},password=#{pwd} where id=#{id}
      </update>
    
      <!-- 删除方法 -->
      <delete id="deleteUser">
      delete from users where id=#{id}
      </delete>
    </mapper>

MyBatis(5)——解决属性名与列名不一致的问题

原文:https://www.cnblogs.com/inkqx/p/12316474.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!