Mybatis 将数据库以下划线连接的字段名(例:"xxx_xxx")自动映射到Java的小驼峰字段

admin 887 2022-09-23

配置方法

  1. yaml配置法:在yaml 中配置map-underscore-to-camel-case: true,如下:
mybatis:
  mapper-locations: mapper/*.xml
  configuration:
    map-underscore-to-camel-case: true
  1. xml配置法:在mybatis-config.xml中配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 在本文档中 <settings>尽量放在<configuration>中第一位,因为标签的出现顺序需遵循规范,后面会详细介绍   -->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <typeAliases>
        <package name="com.xxx.mybatisrundemo01"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///mb"/>
                <property name="username" value="root"/>
                <property name="password" value="xxxx"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com.xxx.dao/user.xml"></mapper>
    </mappers>
</configuration>

效果对比

  1. 数据库中 user表 数据:
+----+-------+-----+----------+-----------+
| id | name  | age | order_id | user_name |
+----+-------+-----+----------+-----------+
|  1 | tom   |  11 |     9057 | xizz      |
|  2 | jerry |  90 |     1057 | tima      |
+----+-------+-----+----------+-----------+
2 rows in set (0.02 sec)
  1. User 内容:
package com.xxx.mybatisrundemo01.model;

public class User {
    private int id ;
    private String name ;
    private int age ;
    private int orderId;
    private String userName;
    
// 篇幅关系,省去getter,setter,toString,构造函数等代码,重点关注User类的属性名与数据库的字段名之间的映射
}
  1. userMapper.xml 内容:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xxx.mybatisrundemo01.dao.userDao">
    
    <select id="listUser" resultType="com.xxx.mybatisrundemo01.model.User">
        select * from user;
    </select>

</mapper>

注意:此处使用resultType直接将select的查询结果映射到User中。随后在service层将结果遍历打印。

未开启map-underscore-to-camel-case的运行结果

10:22:15.987 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Opening JDBC Connection
10:22:16.604 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - Created connection 1970982267.
10:22:16.604 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@757acd7b]
10:22:16.606 [main] DEBUG com.xxx.mybatisrundemo01.dao.userDao.listUser - ==>  Preparing: select * from user;
10:22:16.620 [main] DEBUG com.xxx.mybatisrundemo01.dao.userDao.listUser - ==> Parameters: 
10:22:16.631 [main] DEBUG com.xxx.mybatisrundemo01.dao.userDao.listUser - <==      Total: 2
User{id=1, name='tom', age=11, orderId=0, userName='null'}
User{id=2, name='jerry', age=90, orderId=0, userName='null'}

开启map-underscore-to-camel-case后的运行结果

10:25:21.848 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Opening JDBC Connection
10:25:22.518 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource - Created connection 1019298652.
10:25:22.518 [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@3cc1435c]
10:25:22.521 [main] DEBUG com.xxx.mybatisrundemo01.dao.userDao.listUser - ==>  Preparing: select * from user;
10:25:22.535 [main] DEBUG com.xxx.mybatisrundemo01.dao.userDao.listUser - ==> Parameters: 
10:25:22.558 [main] DEBUG com.xxx.mybatisrundemo01.dao.userDao.listUser - <==      Total: 2
User{id=1, name='tom', age=11, orderId=9057, userName='xizz'}
User{id=2, name='jerry', age=90, orderId=1057, userName='tima'}

附加:xml配置中的标签出现规则

  1. 可以在xml文件中点击标签进行查看子标签的出现顺序,以****标签为例,点击进入后内容如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!--

       Copyright 2009-2016 the original author or authors.

       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.

-->
<!ELEMENT configuration (properties?, settings?, typeAliases?, typeHandlers?, objectFactory?, objectWrapperFactory?, reflectorFactory?, plugins?, environments?, databaseIdProvider?, mappers?)>

篇幅关系,余下无关代码进行省略。

​ 依照文中标签从左到右出现的顺序,可以看到, 标签需要放在等标签前面,否则配置会出现报错。


# Mybatis