SpringBoot+Mybatis开启驼峰映射

mybatis自定义的SQL语句中,如select语句,如果数据库表的字段为驼峰命名,即如img_address这样的形式,那么select语句执行的结果会变成null。

解决办法是在配置文件中加上开启驼峰映射的配置信息。根据配置文件的类型分为以下两种:

1.在.properties文件中添加:

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

但如果已经在.properties中配置了mybatis.config-location=classpath:mybatis/mybatis-config.xml这样的语句,就应该使用下一种方式,即把配置信息写在.xml中。

2.在mybatis的配置文件,如mybatis-config.xml中进行配置:

复制代码复制代码

1
2
3
4
5
6
7
8
<configuration>
<!-- 开启驼峰映射 ,为自定义的SQL语句服务-->
<!--设置启用数据库字段下划线映射到java对象的驼峰式命名属性,默认为false-->
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>

</configuration>

方式一:通过springboot的配置文件application.yml

1
2
3
mybatis:
configuration:
map-underscore-to-camel-case: true

此方式是最简单的,但是要注意,通过springboot的配置文件配置mybatis的设置,则不能够再使用mybatis的配置文件,例如:下边代码中标红的两个设置不能同时存在,要么使用config-location指定mybatis的配置文件,在通过mybatis的配置文件配置相关设置,要么通过springboot配置文件的mybatis.configuration进行相关设置,二者只能选其一,否则会报错。

1
2
3
4
5
mybatis:
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
configuration:
map-underscore-to-camel-case: true

方式二:通过mybatis的配置文件

首先需要在springboot的配置文件application.yml中指定mybatis配置文件的位置。

1
2
3
mybatis:
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml

然后在mybatis配置文件中进行设置

复制代码复制代码

1
2
3
4
5
6
7
8
9
<?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>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>

复制代码复制代码

方式三:通过@Comfiguration注解和@Bean注解,向容器中添加ConfigurationCustomizer类型的组件,在ConfigurationCustomizer中进行设置

复制代码复制代码

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