重构 SQL 构建器。

This commit is contained in:
2023-06-14 16:34:08 +08:00
parent 58e085277b
commit 15ed8c908e
6 changed files with 102 additions and 51 deletions

View File

@@ -8,6 +8,10 @@ public class JdbcSql extends SQL<JdbcSql> {
super();
}
public static JdbcSql newSql() {
return new JdbcSql();
}
@Override
public JdbcSql getSelf() {
return this;

View File

@@ -0,0 +1,65 @@
package xyz.zhouxy.plusone.commons.jdbc;
import com.google.common.annotations.Beta;
@Beta
public class MyBatisSql extends SQL<MyBatisSql> {
private final boolean withScript;
MyBatisSql(boolean withScript) {
super();
this.withScript = withScript;
}
public static MyBatisSql newSql() {
return new MyBatisSql(false);
}
public static MyBatisSql newScriptSql() {
return new MyBatisSql(true);
}
@Override
public MyBatisSql getSelf() {
return this;
}
public static String IN(String col, String paramName) {
return new StringBuilder(" ")
.append(col)
.append(" IN")
.append(buildQuestionsList(col, paramName))
.toString();
}
public static String NOT_IN(String col, String paramName) {
return new StringBuilder()
.append(col)
.append(" NOT IN")
.append(buildQuestionsList(col, paramName))
.toString();
}
private static String buildQuestionsList(String col, String paramName) {
return new StringBuilder()
.append("<foreach item=\"")
.append(col)
.append("\" index=\"index\" collection=\"")
.append(paramName)
.append("\" open=\"(\" separator=\",\" close=\")\">")
.append("#{")
.append(col)
.append("}</foreach>")
.toString();
}
@Override
public String toString() {
String str = super.toString();
if (withScript) {
str = "<script>\n" + str + "\n</script>";
}
return str;
}
}

View File

@@ -30,10 +30,18 @@ public abstract class SQL<T> extends AbstractSQL<T> {
return new JdbcSql();
}
public T WHERE(boolean condition, String sqlConditions) {
public static MyBatisSql newMyBatisSql(boolean withScript) {
return new MyBatisSql(withScript);
}
public T WHERE(boolean condition, String sqlCondition) {
if (condition) {
return WHERE(sqlConditions);
return WHERE(sqlCondition);
}
return getSelf();
}
public T WHERE(boolean condition, String ifSqlCondition, String elseSqlCondition) {
return WHERE(condition ? ifSqlCondition : elseSqlCondition);
}
}

View File

@@ -1,29 +0,0 @@
package xyz.zhouxy.plusone.commons.util;
import java.util.Arrays;
import com.google.common.annotations.Beta;
@Beta
public class MoreArrays {
public static Object[] asObjectArray(final Object... objects) {
return objects;
}
public static char[] newCharArrayWith(int length, char c) {
char[] arr = new char[length];
Arrays.fill(arr, c);
return arr;
}
public static String[] newStringArrayWith(int length, String c) {
String[] arr = new String[length];
Arrays.fill(arr, c);
return arr;
}
private MoreArrays() {
throw new IllegalStateException("Utility class");
}
}