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

问题描述

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

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

问题分析

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

数据库表列:user_name 

实体类属性:user_name

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

数据库表列:user_name 

实体类属性:userName

解决方案

Spring Boot中,可以通过设置map-underscore-to-camel-case属性为true来开启驼峰功能。  

MyBatis配置: 

application.properties中: 

扫描二维码关注公众号,回复: 8965464 查看本文章
#开启驼峰命名转换
mybatis.configuration.map-underscore-to-camel-case=true

application.yml中: 

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

 使用该配置可以让MyBatis自动将SQL中查出来的带下划线命名的字段,自动转换为驼峰命名,再去匹配类中的属性。 

例:

@Select("select phone_num,card_num from xxx where id=#{id}")
public User getUserInfo(String id);

查出来的结果,会被自动转换成phoneNumcardNum,再和结果类(这里就是User )中的属性进行匹配。 

教学视频

DEBUG过程【大概40分钟以后】:https://www.bilibili.com/video/av65117012/?p=23

参考文章

https://segmentfault.com/a/1190000010240142 

https://www.cnblogs.com/leeego-123/p/10725012.html

https://blog.csdn.net/weixin_41758407/article/details/90722718

发布了1371 篇原创文章 · 获赞 237 · 访问量 33万+

猜你喜欢

转载自blog.csdn.net/weixin_43272781/article/details/104145895