sql 语句对应关系显示 _set
package
com20161125;
public
class SqlElementsWrapper {
/*
* oriOutput: {a.*}, {b.*}, a.runId
* alias: a, b
* table: TableA, TabelB
*/
String oriOutput;
String alias;
String table;
public void setAlias() {
if (oriOutput.indexOf("{") > -1) {
this.alias = oriOutput.replace("{", "").replace(".*}", "");
return;
}
this.alias = oriOutput.substring(0, oriOutput.indexOf("."));
}
@Override
public String toString() {
return this.oriOutput + " " + this.alias + " " + this.table;
}
}
package
com20161125;
import
java.util.HashSet;
import
java.util.Set;
public
class GetSqlQueryTest {
public static void main(String[] args) {
Set<SqlElementsWrapper> ss = getOutputElementEntityMap(
"select {a.*},{b.*},a.runId from TableA a,TableB b where a.runId=b.runId");
for (SqlElementsWrapper obj : ss) {
System.out.println(obj.toString());
}
}
private static Set<SqlElementsWrapper> getOutputElementEntityMap(String sql) {
Set<SqlElementsWrapper> set = getOutputAlias(sql);
for (SqlElementsWrapper wrapper : set) {
getTableName(sql, wrapper);
}
return set;
}
private static void getTableName(String sql, SqlElementsWrapper wrapper) {
int beginIndex = sql.indexOf("from") + "from".length();
int endIndex = sql.indexOf("where") == -1 ? sql.length() : sql.indexOf("where");
String popObjStr = sql.substring(beginIndex, endIndex).trim();
String[] arr = popObjStr.split(",");
for (String obj : arr) {
String[] objAlias = obj.split(" ");
String alias = objAlias[1];
if (wrapper.alias.equals(alias)) {
String tableName = objAlias[0];
wrapper.table = tableName;
}
}
}
private static Set<SqlElementsWrapper> getOutputAlias(String sql) {
int beginIndex = sql.indexOf("select") + "select".length();
int endIndex = sql.indexOf("from");
String tempObjStr = sql.substring(beginIndex, endIndex).trim();
String[] arr = tempObjStr.split(",");
Set<SqlElementsWrapper> set = new HashSet<SqlElementsWrapper>();
for (String output : arr) {
SqlElementsWrapper a = new SqlElementsWrapper();
a.oriOutput = output;
a.setAlias();
set.add(a);
}
return set;
}
}