MyBatis配置文件开启驼峰命名映射

mybatis支持属性使用驼峰的命名,用属性是这样的

1 mapUnderscoreToCamelCase:true/false 
2  <!--是否启用下划线与驼峰式命名规则的映射(如first_name => firstName)-->

我们一般在数据库中字段名使用 '_'连接,而在实体类中使用驼峰命名。但是这样查询之后使用的驼峰命名法的是映射不到实体类上的 。

要解决这个问题只需要在mybatis配置文件中添加以下配置

配置是这样的

1 <?xml version="1.0" encoding="UTF-8" ?>  
2 <!DOCTYPE configuration  
3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  
4 "http://mybatis.org/dtd/mybatis-3-config.dtd">  
5 <configuration>  
6     <settings>  
7         <setting name="mapUnderscoreToCamelCase" value="true" />  
8     </settings>  
9 </configuration>

在setting中设置mapUnderscoreToCamelCase为true,就可以实现驼峰转换了, 这个的默认是false

在SpringBoot 项目中没有mybatis.xml文件,可以在application.properties中,加入下面的配置项:

1 mybatis.configuration.mapUnderscoreToCamelCase=true
2 3 mybatis.configuration.map-underscore-to-camel-case=true

设为true表示开启驼峰转换。两种方式实验证明都可以使用。但如果同时配置的话,前者mybatis.configuration.mapUnderscoreToCamelCase的优先级更高。

SpringBoot中还可以使用自定义配置类的方式配置;给容器中添加一个ConfigurationCustomizer;

 1 @Configuration
 2 public class MyBatisConfig {
 3 
 4     @Bean
 5     public ConfigurationCustomizer configurationCustomizer() {
 6         return new ConfigurationCustomizer() {
 7 
 8             @Override
 9             public void customize(org.apache.ibatis.session.Configuration configuration) {
10                 configuration.setMapUnderscoreToCamelCase(true);
11             }
12         };
13     }
14 }

 

posted @ 2022-05-10 22:29  r1-12king  阅读(1405)  评论(0编辑  收藏  举报