跳转到主内容
websoft网络软件专家 - 深耕网络技术,打造实用软件!

如何解决MyBatis中的数据库字段下划线转驼峰_mapUnderscoreToCamelCase全局配置

mapUnderscoreToCamelCase只对自动映射生效,即未定义resultMap、未用@Column/@TableField显式绑定、未在@Select中指定resultMap时才起作用;Spring Boot需在application.yml中配置mybatis.configuration.map-underscore-to-camel-case:true,且resultMap须设autoMapping="true"才能兼顾手动与自动映射。 为什么
mapUnderscoreToCamelCase
设了没用? 多数人配了
mapUnderscoreToCamelCase=true
却发现数据库字段
user_name
还是映射不到 Java 的
userName
,根本原因不是配置写错,而是它只对「自动映射」生效——也就是没有显式写
、纯靠 MyBatis 自己猜列名和属性名时才起作用。 常见错误现象:
User user = mapper.selectById(1);
返回的
user.userName
为
null
,但
user.getUserName()
能取到值(说明 getter 被调用了,但字段没设上)。 只在
mybatis-config.xml
里配了,但 Spring Boot 项目实际走的是
MybatisAutoConfiguration
,得改
application.yml
或
application.properties
用了
@Select
注解 + 自定义 SQL,但没加
resultType
或写了
resultMap
,此时自动映射被跳过 实体类字段用了
@Column(name = "user_name")
或
@Results
,显式覆盖了自动映射逻辑 Spring Boot 下正确开启全局驼峰转换 Spring Boot 2.0+ 默认不读
mybatis-config.xml
,必须通过 Spring 配置项启用。核心是让
Configuration
实例的
mapUnderscoreToCamelCase
属性为
true
,而 Spring Boot 的自动配置会把它从配置文件里拎出来设置。 在
application.yml
中写:
mybatis: configuration: map-underscore-to-camel-case: true
如果用
application.properties
:
mybatis.configuration.map-underscore-to-camel-case=true
确认没在代码里手动 new
SqlSessionFactoryBean
并覆盖
configuration
属性,否则外部配置会被忽略 该配置影响所有未显式指定
resultMap
的
select
语句,包括
@Select
、XML 中的