Commit 52136545 by s_guodong

join查询问题

parent 51a31068
......@@ -33,6 +33,7 @@ public class MybatisArgumentAdapter {
public static enum AdaType {
SELECT("SELECT * FROM %s WHERE %s"),
JOIN_SELECT("SELECT * %s"),
DELETE("DELETE FROM %s WHERE %s");
private String value;
......@@ -92,7 +93,7 @@ public class MybatisArgumentAdapter {
public void init() {
boolean join = false;
sqlParams = new HashMap<>();
String conditions = "";
......@@ -102,20 +103,35 @@ public class MybatisArgumentAdapter {
if (where > -1) {
pattern = pattern.replace("WHERE", "");
}
if (s.contains("FROM")) {
int fromIndex = s.indexOf("WITH");
if (fromIndex == -1) {
fromIndex = s.indexOf("ON");
if (fromIndex > -1) {
fromIndex += 2;
}
} else {
fromIndex += 4;
// 有join的情况
if (s.indexOf("JOIN") > -1) {
join = true;
pattern = AdaType.JOIN_SELECT.value;
Map<String, String> tableMap = new HashMap<>();
String[] split = tableName.split(",");
for (int i = 0; i < split.length; i++) {
String trim = split[i].trim();
tableMap.put(trim.split(" ")[1], trim);
}
if (fromIndex > -1 && where > -1) {
String b = whereSql.substring(fromIndex, where);
whereSql = whereSql.substring(where) + " AND " + b;
String tableStr = whereSql.substring(s.indexOf("FROM") + 4, s.indexOf("LEFT"));
String joinStr = whereSql.substring(s.indexOf("JOIN") + 4);
String[] tableArr = tableStr.split(",");
List<String> tableList = new ArrayList<>();
for (int i = 0; i < tableArr.length; i++) {
tableList.add(tableMap.get(tableArr[i].trim()));
}
String tableNames = " " + String.join(",", tableList) + " ";
String[] joinTableArr = joinStr.split(" ");
for (int i = 0; i < joinTableArr.length; i++) {
String s1 = joinTableArr[i];
if (tableMap.containsKey(s1)) {
joinTableArr[i] = tableMap.get(s1);
}
}
String joinTableNames = String.join(" ", joinTableArr).replace("with", "on").replace("WITH", "ON");
whereSql = whereSql.replace(tableStr, tableNames).replace(joinStr, joinTableNames);
}
if (params != null && params.length > 0) {
conditions = convertPlaceHolder(whereSql, params, sqlParams);
......@@ -130,7 +146,13 @@ public class MybatisArgumentAdapter {
}
}
this.sqlTemplate = String.format(pattern, tableName, conditions);
String sql = "";
if (join) {
sql = String.format(pattern, conditions);
} else {
sql = String.format(pattern, tableName, conditions);
}
this.sqlTemplate = sql;
this.sqlParams.put(HOLDER_SQL, this.sqlTemplate);
this.sqlParams.put(HOLDER_CONDS, conditions);
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment