添加 IN 和 NOT_IN 方法。

feature/net-util
ZhouXY108 2023-06-05 18:31:51 +08:00
parent e40f07fc64
commit 9e30ef5580
2 changed files with 65 additions and 6 deletions

View File

@ -16,6 +16,8 @@
package xyz.zhouxy.plusone.commons.jdbc;
import java.util.Collection;
import org.apache.ibatis.jdbc.AbstractSQL;
import com.google.common.annotations.Beta;
@ -31,11 +33,60 @@ public class SQL extends AbstractSQL<SQL> {
return this;
}
public SQL WHERE_IF(boolean condition, String sqlConditions) {
public static SQL newSql() {
return new SQL();
}
public SQL WHERE(boolean condition, String sqlConditions) {
if (condition) {
return WHERE(sqlConditions);
}
return getSelf();
}
public static String IN(String col, Collection<?> c) {
return IN(col, c.size());
}
public static <T> String IN(String col, T[] c) {
return IN(col, c.length);
}
private static String IN(String col, int length) {
return new StringBuilder()
.append(col)
.append(" IN (")
.append(buildQuestionsList(length))
.append(')')
.toString();
}
public static String NOT_IN(String col, Collection<?> c) {
return NOT_IN(col, c.size());
}
public static <T> String NOT_IN(String col, T[] c) {
return NOT_IN(col, c.length);
}
private static String NOT_IN(String col, int length) {
return new StringBuilder()
.append(col)
.append(" NOT IN (")
.append(buildQuestionsList(length))
.append(')')
.toString();
}
private static String buildQuestionsList(int times) {
char[] arr = new char[times * 3 - 2];
for (int t = 1, i = 0; t <= times; t++) {
arr[i++] = '?';
if (t < times) {
arr[i++] = ',';
arr[i++] = ' ';
}
}
return String.valueOf(arr);
}
}

View File

@ -1,7 +1,9 @@
package xyz.zhouxy.plusone.commons.util;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static xyz.zhouxy.plusone.commons.jdbc.SQL.*;
import java.io.File;
import java.io.IOException;
@ -53,13 +55,19 @@ class SimpleJdbcTemplateTests {
@Test
void testQuery() throws SQLException {
try (Connection conn = this.dataSource.getConnection()) {
Object[] params = MoreArrays.asObjectArray("501533", "501554", "544599");
String sql = newSql()
.SELECT("*")
.FROM("test_table")
.WHERE(NOT_IN("id", params))
.toString();
log.info(sql);
List<DbRecord> rs = SimpleJdbcTemplate.connect(conn)
.queryToRecordList(
"SELECT * FROM public.base_table WHERE id IN (?, ?, ?)",
501533, 501554, 544599);
assertTrue(3 > rs.size());
.queryToRecordList(sql, params);
assertNotNull(rs);
for (DbRecord baseEntity : rs) {
log.info("id: {}", baseEntity.getValueAsLong("id"));
// log.info("id: {}", baseEntity.getValueAsString("id"));
log.info(baseEntity.toString());
assertEquals(Optional.empty(), baseEntity.getValueAsString("updated_by"));
}
}