实现Mybatis中驼峰命名自动转换
2020-06-25 13:33:34
本文总阅读量

在Mybatis中可以通过配置实现驼峰式命名自动转换,简单的实现以下这个小功能。这个也没啥算法可言,就是一个简单的字符串处理,模拟一下就好了。

代码

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
public class autoCamelcase {
public static String[] input; // 用来存下划线命名法的变量名
public static String[] output; // 用来存小驼峰命名法的变量名
public static void main(String[] args) {
initInput();
solve();
print();
}
public static void initInput() {
input = new String[] {
"aaaa_bbbb_ccccc",
"first_name",
"email",
"q_q_q_q_q_q_q"
};
}
public static void solve() {
int n = input.length;
output = new String[n];
for (int i = 0; i < n; i++) { // 处理每一个变量名
int len = input[i].length();
int firstIdx = 0; // 用于存下第一个'_'的位置
while (firstIdx < len && input[i].charAt(firstIdx) != '_') {
firstIdx++;
}
if (firstIdx == len) { // 如果没有下划线则两种命名方式相同
output[i] = input[i];
} else {
output[i] = "";
output[i] += input[i].substring(0, firstIdx);
for (int l = firstIdx, r = firstIdx; l < len; r++, l = r) { // 在每一次循环中l,r分别指向 _xxxxxxxxxx 然后模拟就好了
while (r + 1 < len && input[i].charAt(r + 1) != '_') r++; // ^ ^
output[i] += (char)(input[i].charAt(l + 1) - 32); // | |
if (l + 2 <= r) { // l r
output[i] += input[i].substring(l + 2, r + 1);
}
}
}
}
}
public static void print() {
for (String v : output) {
System.out.println(v);
}
}
}

结果