Mybatis log里sql拼接用工具类
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SqlEdit {
private static final String PREPARING = "Preparing";
private static final String PARAMETERS = "Parameters";
public static String sqlStr = "==> Preparing: select * from tablename where name = ? \r\n"
+ "==> Parameters: tom(String), "
+ ""
+ ""
+ ""
+ "";
public static void main(String[] args) {
SqlEdit sqlEdit = new SqlEdit();
System.out.println(sqlEdit.sql(sqlStr));
}
public String sql(String sqlStr) {
String sqltext = getSql(sqlStr);
List<String> paramList = getSubParam(getParam(sqlStr));
for (String p : paramList) {
sqltext = sqltext.replaceFirst("\\?", p);
}
return sqltext;
}
private String getSql(String str) {
String regexSql = PREPARING + ":(.*)\\r\\n";
return getStr(regexSql, str);
}
private String getParam(String str) {
String regexParam = PARAMETERS + ":(.*)\\r\\n";
return getStr(regexParam, str);
}
private List<String> getSubParam(String strPar) {
String regex = "([\\u2E80-\\u9FFF\\d\\w\\d.d]*)\\((.*)\\)";
Pattern pattern = Pattern.compile(regex) ;
String[] aStr = strPar.split(",");
List<String> parList = new ArrayList<String>();
for (int i = 0; i < aStr.length; i++) {
if ("null".equals(aStr[i].trim())) {
parList.add("null");
continue;
}
Matcher matcher = pattern.matcher(aStr[i]);
if (!matcher.find()) {
continue;
}
if ("String".equals(matcher.group(2))) {
parList.add("'" + matcher.group(1) + "'");
} else {
parList.add(matcher.group(1));
}
}
return parList;
}
private String getStr(String regex, String str) {
Pattern pattern = Pattern.compile(regex) ;
Matcher matcher = pattern.matcher(str);
return matcher.find()? matcher.group(1).trim(): "";
}
}
拼接后的结果
select * from tablename where name = 'tom';