Java操作mysql字段转换驼峰并加别名
整合了部分转换驼峰的代码,另外加上加别名的功能。
工具类代码
代码
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MysqlAliasUtils {
private static final Pattern UNDERLINE_PATTERN = Pattern.compile("_([a-z])");
private static final Pattern FIRST_UPPERCASE = Pattern.compile("([a-z])");
public static void main(String[] args) {
String sql="id,sku_id,spu_id,category,create_ts,update_ts,delete_flag";
String alias="good";
sql=setMysqlAlias(sql,alias);
}
/**
* 转换字段为驼峰格式并加上表别名,表别名格式可自己调整
* @param sql
* @param alias
* @return
*/
private static String setMysqlAlias(String sql, String alias) {
if(sql==null||!sql.contains(",")||alias==null){
return null;
}
StringBuilder result= new StringBuilder();
String[] split = sql.split(",");
List<String> sqlColumnList = Arrays.asList(split);
List<String>firstUppercaseStrList=new ArrayList<>();
for (int i = 0; i < sqlColumnList.size(); i++) {
String s = sqlColumnList.get(i);
String underlineToHumpStr = underlineToHump(s);
String firstUppercaseStr = firstUppercase(underlineToHumpStr);
s=","+alias+"."+s+" "+alias+firstUppercaseStr;
sqlColumnList.set(i,s);
result.append(s);
firstUppercaseStrList.add(alias+firstUppercaseStr);
}
//System.out.println(sqlColumnList);
//result需要去掉最前面的逗号
System.out.println(result);
System.out.println(firstUppercaseStrList);
return result.toString();
}
/**
* 根据传入的带下划线的字符串转化为驼峰格式
* @param str
* @author mrf
* @return
*/
public static String underlineToHump (String str){
//正则匹配下划线及后一个字符,删除下划线并将匹配的字符转成大写
Matcher matcher = UNDERLINE_PATTERN.matcher(str);
StringBuffer sb = new StringBuffer(str);
if (matcher.find()) {
sb = new StringBuffer();
//将当前匹配的子串替换成指定字符串,并且将替换后的子串及之前到上次匹配的子串之后的字符串添加到StringBuffer对象中
//正则之前的字符和被替换的字符
matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
//把之后的字符串也添加到StringBuffer对象中
matcher.appendTail(sb);
} else {
//去除除字母之外的前面带的下划线
return sb.toString().replaceAll("_", "");
}
return underlineToHump(sb.toString());
}
/**
* 将传入的驼峰字段字符串首字母转为大写
* @param str
* @return
*/
public static String firstUppercase(String str){
Matcher matcher = FIRST_UPPERCASE.matcher(str);
StringBuffer sb = new StringBuffer(str);
if (matcher.find()) {
sb = new StringBuffer();
//将当前匹配的子串替换成指定字符串,并且将替换后的子串及之前到上次匹配的子串之后的字符串添加到StringBuffer对象中
//正则之前的字符和被替换的字符
matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
//把之后的字符串也添加到StringBuffer对象中
matcher.appendTail(sb);
} else {
return sb.toString();
}
return underlineToHump(sb.toString());
}
}