Mybatis 返回resultType=“map“映射下划线转驼峰

Mybatis 返回resultType=“map“映射下划线转驼峰示例

1
<select id="getMyList" parameterType="map" resultType="map">

1、增加如下配置类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
@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();
}
}
}

2、application.yml文件增加如下配置:

1
2
3
4
mybatis:
configuration:
#开启自动下划线格式转驼峰格式
map-underscore-to-camel-case: true

Mybatis 返回resultType=“map“映射下划线转驼峰

https://www.sgknight.cn/2022/03/23/mybatis-return-resultType-map-useCamelCaseMapping/

作者

knight

发布于

2022-03-23

更新于

2022-03-23

许可协议

评论