zoukankan      html  css  js  c++  java
  • MyBatis(5)——解决属性名与列名不一致的问题

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

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

    • 说明: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>
      
  • 相关阅读:
    (转)树状数组
    poj 3041 Asteroids(二分图最小顶点覆盖)
    poj 2513 Colored Sticks
    (转)优先队列的用法 附:poj2442 poj1442
    poj 1094 Sorting It All Out (拓补)
    poj 3026 Borg Maze(bfs+最小生成树)
    poj 3349 Snowflake Snow Snowflakes
    poj 3020 Antenna Placement(二分图的最大匹配)
    mysql explain
    php strtotime
  • 原文地址:https://www.cnblogs.com/inkqx/p/12316474.html
Copyright © 2011-2022 走看看