zoukankan      html  css  js  c++  java
  • Mybatis——实体类属性名和数据库字段名不同时的解决办法

    在使用Mybatis来持久化数据库时,有时候会碰到数据库中表中的字段与java实体类中属性名不一致的情况,在这种情况下Mybatis是不能完成字段的自动映射的。而通常情况下,数据库及实体类是不应该被改的的。所以要在不改变数据库以及实体类的情况下解决这个问题,下面是解决该问题的三种方式:

    java实体类:

    public class User
    {
        private Long id;
        private String userName;
        private String passWord;
        /**
         * ...
         * get,set方法不再列出
         * ...
         * */
    }

    1.既然是因为名字不一致而导致Mybatis不能完成自动映射,那么就可以将两者的名字想办法保持一致,为查询出的数据库字段起个别名就可以,实例如下:

    <select id="selectUserById" resultType="User">
            select 
            id,
            user_name as userName,<!--不用在意大小写,Mybatis会先转换成大写再进行匹配  -->
            user_password as userPassword,
            from user
            where id = #{id}
    </select>


    2.另一种解决名字不一致的方式是事先指定映射关系,这样Mybatis也能自动完成映射。Mybatis提供了resultMap可以指定映射关系,示例如下:

      type 属性:指定实体类的全限定类名
      id 属性:给定一个唯一标识,是给查询 select 标签引用用的。
    <resultMap type="User" id="UserResultMap">
          id 标签:用于指定主键字段
          result 标签:用于指定非主键字段
          column 属性:用于指定数据库列名
          property 属性:用于指定实体类属性名称
            <id column="id" property="id"/>
            <result column="user_name" property="userName"/>
            <result column="user_password" property="userPassword"/>
    </resultMap>
        
        
    <select id="selectUserById" resultMap="UserResultMap">
            select 
            id,
            user_name,
            user_password,
            from user
            where id = #{id}
    </select>


    注意:
    1.使用resultMap时,在select语句配置中,要有resultMap替换原来的resultType。

    2.resultMap中的column要与查询到的字段名一致,property要与实体类的属性一致。

    3.在通常情况下,java中的实体类中的属性一般是采用驼峰命名命名的,而数据库中表的字段则用下划线区分字母。在这种情况下,Mybatis提供了一个全局属性mapUnderscoreToCamelCase来解决两者名字不一致的问题。

    <settings>
        <!--其他配置...  -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!--其他配置...  -->
    </settings>

    注意:因为该属性是全局属性,所以需要配置在Mybatis的配置文件中,而不是Mapper.xml映射文件中。

  • 相关阅读:
    [LeetCode] 374. Guess Number Higher or Lower
    [LeetCode] 35. Search Insert Position
    [LeetCode] 205. Isomorphic Strings
    [LeetCode] 87. Scramble String
    [LeetCode] 274. H-Index
    [LeetCode] 507. Perfect Number
    [LeetCode] 88. Merge Sorted Array
    [LeetCode] 283. Move Zeroes
    [LeetCode] 287. Find the Duplicate Number
    [LeetCode] 204. Count Primes
  • 原文地址:https://www.cnblogs.com/yscec/p/12041747.html
Copyright © 2011-2022 走看看