业务需求
有时候需要通过 Map 作为请求体接收 Post 请求传递过来的数据。而前端传递来的字段是驼峰命名法规则的字段,在使用时希望多一层自动转换。
特别是,希望在 update 语句中,遍历 map 的字段和值,循环遍历插入,减少写 update 的字段和 values 字段(偷懒罢了)。
<update id="update">
UPDATE orders
<trim prefix="SET" suffixOverrides=",">
<foreach collection="map" item="value" index="key">
${key} = #{value},
</foreach>
</trim>
WHERE id = #{id};
</update>
工具类
一个转换 Map 中 key 为驼峰命名法规则为下划线命名法的工具类:
public record ToUnderscore(Map<String, Object> map) {
record NewMapKey(String oldKey, String newKey, Object value) {
}
private void replace(ArrayList<NewMapKey> list) {
for (NewMapKey item : list) {
map.remove(item.oldKey());
map.put(item.newKey(), item.value());
}
}
public void convert() {
String regEx = "[A-Z]";
Pattern pattern = Pattern.compile(regEx);
ArrayList<NewMapKey> list = new ArrayList<>();
for (String oldKey : map.keySet()) {
Matcher matcher = pattern.matcher(oldKey);
while (matcher.find()) {
StringBuilder sb = new StringBuilder(oldKey);
String newKey = "_" + matcher.group().toLowerCase();
sb.replace(matcher.start(), matcher.start() + 1, newKey);
list.add(new NewMapKey(oldKey, sb.toString(), map.get(oldKey)));
}
}
replace(list);
}
}
使用方式
在 Service 类中对业务进行处理:
public R<Object> update(Map<String, Object> map, Integer id) {
try {
map.remove("items");
map.remove("id");
// 这里调用,把 map 传递进去进行转换
ToUnderscore tu = new ToUnderscore(map);
tu.convert(); // 开始转换,tu.map() 获取转换过后的 map
int flag = mapper.update(tu.map(), id);
if (flag != 0) return R.build(Status.OK, "更新数据成功");
else return R.build(Status.NO, "操作失败");
} catch (Exception e) {
e.printStackTrace();
return R.build(Status.NO, "服务器错误");
}
}