本想实现 mybatis 返回 Map 转驼峰的功能,但是之前配置了 mybatis.configLocation 转换不生效
在 application.xml 中不使用单独的 xml 配置,直接使用 configuration 的配置就生效
mybatis.configuration.map-underscore-to-camel-case: true
configuration 又与 configLocation 不能共存
求指导大神指导在使用 configLocation 配置的时候,使我的转换生效
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.wrapper.MapWrapper;
import org.apache.ibatis.reflection.wrapper.ObjectWrapper;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Map;
@Configuration
public class MybatisConfig {
/**
* mybatis resultType 为 map 时下划线键值转小写驼峰形式插
*/
@Bean
public ConfigurationCustomizer configurationCustomizer() {
return configuration -> configuration.setObjectWrapperFactory(new MapWrapperFactory());
}
static class MapWrapperFactory implements ObjectWrapperFactory {
@Override
public boolean hasWrapperFor(Object object) {
return object != null && object instanceof Map;
}
@Override
public ObjectWrapper getWrapperFor(MetaObject metaObject, Object object) {
return new MyMapWrapper(metaObject, (Map) object);
}
}
static class MyMapWrapper extends MapWrapper {
MyMapWrapper(MetaObject metaObject, Map<String, Object> map) {
super(metaObject, map);
}
@Override
public String findProperty(String name, boolean useCamelCaseMapping) {
if (useCamelCaseMapping
&& ((name.charAt(0) >= 'A' && name.charAt(0) <= 'Z')
|| name.contains("_"))) {
return underlineToCamelhump(name);
}
return name;
}
/**
* 将下划线风格替换为驼峰风格
*
* @param inputString
* @return
*/
private String underlineToCamelhump(String inputString) {
StringBuilder sb = new StringBuilder();
boolean nextUpperCase = false;
for (int i = 0; i < inputString.length(); i++) {
char c = inputString.charAt(i);
if (c == '_') {
if (sb.length() > 0) {
nextUpperCase = true;
}
} else {
if (nextUpperCase) {
sb.append(Character.toUpperCase(c));
nextUpperCase = false;
} else {
sb.append(Character.toLowerCase(c));
}
}
}
return sb.toString();
}
}
}
1
vishun 2022-09-06 16:58:10 +08:00
你可以参考下[若依]( https://github.com/yangzongzhuan/RuoYi-Vue/blob/master/ruoyi-admin/src/main/resources/application.yml)的,它是`configLocation`中指向的`xml`中配置的,不过它注释掉了,取消注释即可
|
2
liusir OP @vishun 不是这个,添加这个<setting name="mapUnderscoreToCamelCase" value="true"/>只能是对返回的实体进行映射,我是想返回的类型是 Map 的时候自动转换
|
3
RedBeanIce 2022-09-07 11:26:43 +08:00
如果你 resultType 是 map 就不会自动转换吗?,map 的 key 还是下划线吗?我去试试。
稍后回复 |
4
RedBeanIce 2022-09-07 22:19:09 +08:00
https://imgse.com/i/vbE1PJ
我觉得您可以试一下拦截器的做法,如图所示 https://github.com/WarriorFromLongAgo/xue-gao-write-and-use 分支:spring_mybatis 类:执行完建表 sql ,执行测试类 ResultServiceTest ,debug 断点 PrintSqlInterceptor |
5
RedBeanIce 2022-09-07 22:20:07 +08:00
另外,Java 问题最好在 Java 分类问问题,在程序员分类里面问,Javaer 们可能不会来这里看。
|