前言,没时间解释了,先贴代码
1.新增自定义Visitor
代码语言:javascript复制 /**
* 自定义Visitor ,这里是MySQL,其他数据库请自行更换
**/
public static class MyReplaceTableVisitor extends MySqlASTVisitorAdapter {
private final String databaseName;
public MyReplaceTableVisitor(String databaseName) {
this.databaseName = databaseName;
}
@Override
public boolean visit(SQLExprTableSource x) {
String originTableName = x.getExpr().toString();
if (databaseName != null) {
if (originTableName.contains(".")) {
return true;
}
//修改表名
x.setExpr(databaseName "." originTableName);
logger.info(" replace table:" originTableName " -> " databaseName "." originTableName);
}
return true;
}
}
2.替换方法
代码语言:javascript复制 public static String replaceTableName(String sql, String tableName) {
if (tableName == null) {
return sql;
}
List<SQLStatement> statements = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL);
MyReplaceTableVisitor visitor = new MyReplaceTableVisitor(tableName);
for (SQLStatement stmt : statements) {
stmt.accept(visitor);
}
return SQLUtils.toSQLString(statements, JdbcConstants.MYSQL);
}
调用测试方法
代码语言:javascript复制 public static void main(String[] args) {
String sql = "select c.*, (select a.name as province_name from portal_area a where a.id = c.province_id) as province_name, (select a.name as city_name from portal_area a where a.id = c.city_id) as city_name, (CASE WHEN c.area_id IS NULL THEN NULL ELSE (select a.name as area_name from portal_area a where a.id = c.area_id) END )as area_name from portal.portal_company c where no = ?";
String s = replaceTableName(sql, "abc");
System.out.println(s);
}