zoukankan      html  css  js  c++  java
  • MyBatis 实体类属性与表字段不一致

    因为数据库一般设置为表的字段不区分大小写,所以数据库中表的字段通常是以 _ 来进行词组划分的,比如 user 表中字段名会有: user_id、user_name、user_pwd :

    create table user(  
       user_id int pramary key not null,  
       user_name varchar(20) not null,  
       user_pwd varchar(20) not null  
    )  

    但是 User 的实体类一般会写为:

    public class User{  
        private int userId ;  
        private String userName;  
        private String userPwd;  
    }  

    这是由于 JAVA 是区分大小写的,可以采用驼峰标识来进行词组划分。而在这种情况下 Mybatis 无法完成字段的自动映射。但我们又不应该直接更改数据库及实体类。所以有解决该问题的三种方式:

    1.起别名

    在 SQL 语句中为字段名标记与实体类属性相同的名称:

    <select id="selectUserById" resultType="User">  
            select   
                user_id as userId ,  
                user_name as userName,
                user_pwd as userPwd,  
            from user  
            where user_id = #{userId}  
    </select>  

    2.resultMap指定映射关系

    <resultMap type="User" id="UserResultMap">  
            <id column="user_id" property="userId"/>  
            <result column="user_name" property="userName"/>  
            <result column="user_pwd" property="userPwd"/>  
    </resultMap>  
    
    
    <select id="selectUserById" resultMap="UserResultMap">  
            select   
                user_id,  
                user_name,  
                user_pwd,  
            from user  
            where user_id= #{user_id}  
    </select>  

    注意:
    1.使用resultMap时,在select语句配置中,要有resultMap替换原来的resultType。
    2.resultMap中的column要与查询到的字段名一致,property要与实体类的属性一致。

    3.Mybatis 全局属性 mapUnderscoreToCamelCase

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

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

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

  • 相关阅读:
    nginx文件类型错误解析漏洞
    js 获取URL中的参数并转换为对象
    postman
    php curl参数详解
    php 两变量值互换 方法
    PHP 命名空间与spl_autoload_register() 自动加载机制
    php命名大小问题
    PHP实现冒泡排序
    使用 PHPStorm + Xdebug 实现断点调试(二)
    TSPL学习笔记(2):过程和变量绑定
  • 原文地址:https://www.cnblogs.com/Sherlock-J/p/12925985.html
Copyright © 2011-2022 走看看