Spring Boot-MyBatis配置带下划线命名的字段自动转换驼峰命名解决方案

1,042 阅读1分钟

问题描述
MyBatis无法查询出属性名和数据库字段名不完全相同的数据。

即:属性名和数据库字段名分别为驼峰命名和下划线命名时查出的数据为NULL。

问题分析
MyBatis默认是属性名和数据库字段名一一对应的,即 

数据库表列:user_name 

实体类属性:user_name

但是java中一般使用驼峰命名 

数据库表列:user_name 

实体类属性:userName

实体类属性:userName

解决方案 (开启驼峰命名转换)
在Spring Boot中,可以通过设置map-underscore-to-camel-case属性为true来开启驼峰功能。  

MyBatis配置: 

application.properties中:

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

application.yml中: 

mybatis:
  configuration:
    map-underscore-to-camel-case: true