Parcourir la source

update jpa builder.

deason il y a 6 ans
Parent
commit
aa7b1ced2e

+ 2 - 0
examcloud-core-print-common/src/main/java/cn/com/qmth/examcloud/core/print/common/jpa/OrderBuilder.java

@@ -13,6 +13,8 @@ import java.util.ArrayList;
 import java.util.List;
 
 /**
+ * 排序条件构建类
+ *
  * @author: fengdesheng
  * @since: 2018/10/23
  */

+ 2 - 0
examcloud-core-print-common/src/main/java/cn/com/qmth/examcloud/core/print/common/jpa/SearchBuilder.java

@@ -14,6 +14,8 @@ import java.util.Collection;
 import java.util.List;
 
 /**
+ * 常用的查询条件构建类
+ *
  * @author: fengdesheng
  * @since: 2018/10/23
  */

+ 74 - 7
examcloud-core-print-common/src/main/java/cn/com/qmth/examcloud/core/print/common/jpa/SpecUtils.java

@@ -15,11 +15,12 @@ import org.springframework.data.jpa.domain.Specifications;
 
 import javax.persistence.criteria.Path;
 import javax.persistence.criteria.Predicate;
+import javax.validation.constraints.NotNull;
 import java.util.ArrayList;
 import java.util.List;
 
 /**
- * JPA查询工具
+ * JPA Spec常用的查询封装
  *
  * @author: fengdesheng
  * @since: 2018/10/17
@@ -34,10 +35,25 @@ public class SpecUtils {
      */
     public static final int DEFAULT_PAGE_SIZE = 10;
 
+    /**
+     * 构建分页条件
+     *
+     * @param pageNo
+     * @param pageSize
+     * @return
+     */
     public static Pageable buildPageable(Integer pageNo, Integer pageSize) {
         return buildPageable(pageNo, pageSize, null);
     }
 
+    /**
+     * 构建分页条件
+     *
+     * @param pageNo
+     * @param pageSize
+     * @param sort
+     * @return
+     */
     public static Pageable buildPageable(Integer pageNo, Integer pageSize, Sort sort) {
         if (pageNo == null || pageNo < 1) {
             pageNo = DEFAULT_PAGE_NO;
@@ -48,10 +64,27 @@ public class SpecUtils {
         return new PageRequest(pageNo - 1, pageSize, sort);
     }
 
+    /**
+     * 构建查询条件
+     *
+     * @param clazz
+     * @param searchers
+     * @param <T>
+     * @return
+     */
     public static <T> Specification<T> buildSearchers(final Class<T> clazz, final List<SearchBuilder.Searcher> searchers) {
         return buildSearchers(clazz, searchers, false);
     }
 
+    /**
+     * 构建查询条件
+     *
+     * @param clazz
+     * @param searchers
+     * @param isOR
+     * @param <T>
+     * @return
+     */
     public static <T> Specification<T> buildSearchers(final Class<T> clazz, final List<SearchBuilder.Searcher> searchers, final boolean isOR) {
         if (searchers == null || searchers.size() == 0) {
             return null;
@@ -122,14 +155,48 @@ public class SpecUtils {
         };
     }
 
-    public static Specification andMerge(Specification target1, Specification target2) {
-        return Specifications.where(target1).and(target2);
+    /**
+     * 合并查询条件
+     *
+     * @param specs
+     * @return
+     */
+    public static Specification andMerge(@NotNull Specification... specs) {
+        if (specs == null || specs.length == 0) {
+            return null;
+        }
+        Specifications result = null;
+        for (int i = 0; i < specs.length; i++) {
+            if (i == 0) {
+                result = Specifications.where(specs[i]);
+                continue;
+            }
+            result = Specifications.where(result).and(specs[i]);
+        }
+        return result;
     }
 
-    public static Specification orMerge(Specification target1, Specification target2) {
-        // 注:SQL中AND优先级高于OR
-        // 示例:... t.name='' or t.age=1 and t.gender=1 等于 ... t.name='' or (t.age=1 and t.gender=1)
-        return Specifications.where(target1).or(target2);
+    /**
+     * 合并查询条件
+     * 注:SQL中AND优先级高于OR
+     * 示例:... t.name='' or t.age=1 and t.gender=1 等同于 ... t.name='' or (t.age=1 and t.gender=1)
+     *
+     * @param specs
+     * @return
+     */
+    public static Specification orMerge(@NotNull Specification... specs) {
+        if (specs == null || specs.length == 0) {
+            return null;
+        }
+        Specifications result = null;
+        for (int i = 0; i < specs.length; i++) {
+            if (i == 0) {
+                result = Specifications.where(specs[i]);
+                continue;
+            }
+            result = Specifications.where(result).or(specs[i]);
+        }
+        return result;
     }
 
 }

+ 96 - 52
examcloud-core-print-common/src/main/java/cn/com/qmth/examcloud/core/print/common/jpa/SqlWrapper.java

@@ -9,49 +9,38 @@ package cn.com.qmth.examcloud.core.print.common.jpa;
 
 import java.util.Collection;
 
+import static cn.com.qmth.examcloud.core.print.common.jpa.SqlWrapper.Constant.*;
+
 /**
- * 原生SQL包装类
+ * SQL常用的语句构建
  *
  * @author: fengdesheng
  * @since: 2018/10/17
  */
 public class SqlWrapper {
-    private static final String SELECT = "SELECT ";
-    private static final String UPDATE = "UPDATE ";
-    private static final String DELETE = "DELETE ";
-    private static final String SET = " SET ";
-    private static final String COUNT = " COUNT ";
-    private static final String SUM = " SUM ";
-    private static final String DISTINCT = " DISTINCT ";
-    private static final String FROM = " FROM ";
-    private static final String WHERE = " WHERE ";
-    private static final String INNER_JOIN = " INNER JOIN ";
-    private static final String LEFT_JOIN = " LEFT JOIN ";
-    private static final String UNION_ALL = " UNION ALL ";
-    private static final String UNION = " UNION ";
-    private static final String ON = " ON ";
-    private static final String AS = " AS ";
-    private static final String AND = " AND ";
-    private static final String OR = " OR ";
-    private static final String LIKE = " LIKE ";
-    private static final String IN = " IN ";
-    private static final String NOT_IN = " NOT IN ";
-    private static final String IS_NULL = " IS NULL ";
-    private static final String IS_NOT_NULL = " IS NOT NULL ";
-    private static final String GROUP_BY = " GROUP BY ";
-    private static final String ORDER_BY = " ORDER BY ";
-    private static final String ASC = " ASC ";
-    private static final String DESC = " DESC ";
-
     private StringBuilder sql = new StringBuilder();
 
+    public String build() {
+        return sql.toString();
+    }
+
+    public SqlWrapper append(String str) {
+        sql.append(str);
+        return this;
+    }
+
+    public SqlWrapper as(String name) {
+        sql.append(AS).append(name);
+        return this;
+    }
+
     public SqlWrapper select() {
         sql.append(SELECT).append("*");
         return this;
     }
 
     public SqlWrapper select(String columns) {
-        /* 多个按逗号分隔 */
+        /* 多个字段须按逗号分隔 */
         sql.append(SELECT).append(columns);
         return this;
     }
@@ -101,6 +90,31 @@ public class SqlWrapper {
         return this;
     }
 
+    public SqlWrapper rightJoin(String tableName) {
+        sql.append(RIGHT_JOIN).append(tableName);
+        return this;
+    }
+
+    public SqlWrapper union(String otherQuerySql) {
+        sql.append(UNION).append(otherQuerySql);
+        return this;
+    }
+
+    public SqlWrapper unionAll(String otherQuerySql) {
+        sql.append(UNION_ALL).append(otherQuerySql);
+        return this;
+    }
+
+    public SqlWrapper exists(String subQuerySql) {
+        sql.append(EXISTS).append("(").append(subQuerySql).append(")");
+        return this;
+    }
+
+    public SqlWrapper notExists(String subQuerySql) {
+        sql.append(NOT_EXISTS).append("(").append(subQuerySql).append(")");
+        return this;
+    }
+
     public SqlWrapper on(String fieldName, String refFieldName) {
         sql.append(ON).append(fieldName).append(" = ").append(refFieldName);
         return this;
@@ -111,6 +125,12 @@ public class SqlWrapper {
         return this;
     }
 
+    public SqlWrapper oneEqOne() {
+        /* default condition */
+        sql.append("1=1").append(AND);
+        return this;
+    }
+
     public SqlWrapper and() {
         sql.append(AND);
         return this;
@@ -131,12 +151,12 @@ public class SqlWrapper {
         return this;
     }
 
-    public SqlWrapper eq(String fieldName, Number value) {
+    public SqlWrapper eq(String fieldName, CharSequence value) {
         sql.append(fieldName).append(" = ").append("'").append(value).append("'");
         return this;
     }
 
-    public SqlWrapper eq(String fieldName, CharSequence value) {
+    public SqlWrapper eq(String fieldName, Number value) {
         sql.append(fieldName).append(" = ").append("'").append(value).append("'");
         return this;
     }
@@ -208,13 +228,19 @@ public class SqlWrapper {
         return this;
     }
 
-    public SqlWrapper isNotNull(String fieldName) {
+    public SqlWrapper notNull(String fieldName) {
         sql.append(fieldName).append(IS_NOT_NULL);
         return this;
     }
 
+    public SqlWrapper groupBy(String columns) {
+        /* 多个字段时须按逗号分隔 */
+        sql.append(GROUP_BY).append(columns);
+        return this;
+    }
+
     public SqlWrapper orderBy(String columns, boolean isDesc) {
-        /* 多个按逗号分隔 */
+        /* 多个字段时须按逗号分隔 */
         if (isDesc) {
             sql.append(ORDER_BY).append(columns).append(DESC);
         } else {
@@ -223,35 +249,20 @@ public class SqlWrapper {
         return this;
     }
 
-    public SqlWrapper groupBy(String columns) {
-        /* 多个按逗号分隔 */
-        sql.append(GROUP_BY).append(columns);
+    public SqlWrapper having() {
+        sql.append(HAVING);
         return this;
     }
 
-    public SqlWrapper as(String name) {
-        sql.append(AS).append(name);
-        return this;
-    }
-
-    public SqlWrapper append(String str) {
-        sql.append(str);
-        return this;
-    }
-
-    public String build() {
-        return sql.toString();
-    }
-
     private String spilt(Collection<?> values) {
         if (values == null || values.size() == 0) {
             throw new IllegalArgumentException("Values must be not empty.");
         }
-        int index = 0, total = values.size();
         StringBuilder str = new StringBuilder();
+        int index = 0, total = values.size();
         for (Object value : values) {
             if (!(value instanceof CharSequence || value instanceof Number)) {
-                throw new IllegalArgumentException("Values must be charSequence or number.");
+                throw new IllegalArgumentException("Values must be String or Number.");
             }
             str.append(value.toString());
             if (index < (total - 1)) {
@@ -262,4 +273,37 @@ public class SqlWrapper {
         return str.toString();
     }
 
+    interface Constant {
+        String SELECT = " SELECT ";
+        String UPDATE = " UPDATE ";
+        String DELETE = " DELETE ";
+        String SET = " SET ";
+        String COUNT = " COUNT ";
+        String SUM = " SUM ";
+        String DISTINCT = " DISTINCT ";
+        String FROM = " FROM ";
+        String WHERE = " WHERE ";
+        String INNER_JOIN = " INNER JOIN ";
+        String RIGHT_JOIN = " RIGHT JOIN ";
+        String LEFT_JOIN = " LEFT JOIN ";
+        String UNION = " UNION ";
+        String UNION_ALL = " UNION ALL ";
+        String EXISTS = " EXISTS ";
+        String NOT_EXISTS = " NOT EXISTS ";
+        String ON = " ON ";
+        String AS = " AS ";
+        String AND = " AND ";
+        String OR = " OR ";
+        String LIKE = " LIKE ";
+        String IN = " IN ";
+        String NOT_IN = " NOT IN ";
+        String IS_NULL = " IS NULL ";
+        String IS_NOT_NULL = " IS NOT NULL ";
+        String GROUP_BY = " GROUP BY ";
+        String ORDER_BY = " ORDER BY ";
+        String HAVING = " HAVING ";
+        String ASC = " ASC ";
+        String DESC = " DESC ";
+    }
+
 }

+ 21 - 4
examcloud-core-print-starter/src/test/java/cn/com/qmth/examcloud/core/print/test/PrintingProjectServiceTest.java

@@ -11,6 +11,7 @@ import cn.com.qmth.examcloud.core.print.PrintApplication;
 import cn.com.qmth.examcloud.core.print.common.jpa.OrderBuilder;
 import cn.com.qmth.examcloud.core.print.common.jpa.SearchBuilder;
 import cn.com.qmth.examcloud.core.print.common.jpa.SpecUtils;
+import cn.com.qmth.examcloud.core.print.common.jpa.SqlWrapper;
 import cn.com.qmth.examcloud.core.print.common.utils.JsonMapper;
 import cn.com.qmth.examcloud.core.print.entity.PrintingProject;
 import cn.com.qmth.examcloud.core.print.repository.PrintingProjectRepository;
@@ -20,6 +21,8 @@ import org.junit.runner.RunWith;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.test.context.SpringBootTest;
 import org.springframework.data.jpa.domain.Specification;
+import org.springframework.jdbc.core.BeanPropertyRowMapper;
+import org.springframework.jdbc.core.JdbcTemplate;
 import org.springframework.test.context.junit4.SpringRunner;
 
 import java.util.List;
@@ -35,9 +38,11 @@ public class PrintingProjectServiceTest {
     private PrintingProjectService printingProjectService;
     @Autowired
     private PrintingProjectRepository printingProjectRepository;
+    @Autowired
+    private JdbcTemplate jdbcTemplate;
 
-    @Test
-    public void demoTest() throws Exception {
+    //@Test
+    public void specTest() throws Exception {
         //查询条件1
         SearchBuilder searchBuilder1 = new SearchBuilder().eq("orgName", "abc");
         Specification<PrintingProject> spec1 = SpecUtils.buildSearchers(PrintingProject.class, searchBuilder1.build());
@@ -46,9 +51,13 @@ public class PrintingProjectServiceTest {
         SearchBuilder searchBuilder2 = new SearchBuilder().eq("orgId", 1L).eq("examId", 1L);
         Specification<PrintingProject> spec2 = SpecUtils.buildSearchers(PrintingProject.class, searchBuilder2.build(), true);
 
+        //查询条件3
+        SearchBuilder searchBuilder3 = new SearchBuilder().eq("pmId", 1L).eq("supplierId", 1L);
+        Specification<PrintingProject> spec3 = SpecUtils.buildSearchers(PrintingProject.class, searchBuilder3.build());
+
         //合并查询条件
-        //Specification<PrintingProject> spec = SpecUtils.orMerge(spec1, spec2);
-        //Specification<PrintingProject> spec = SpecUtils.andMerge(spec1, spec2);
+//        Specification<PrintingProject> spec = SpecUtils.orMerge(spec1, spec2, spec3);
+//        Specification<PrintingProject> spec = SpecUtils.andMerge(spec1, spec2, spec3);
         Specification<PrintingProject> spec = SearchBuilder.EQ("orgId", 1L);
 
         OrderBuilder orderBuilder = new OrderBuilder().desc("id");
@@ -56,4 +65,12 @@ public class PrintingProjectServiceTest {
         System.out.println(new JsonMapper().toJson(list));
     }
 
+    @Test
+    public void sqlTest() throws Exception {
+        SqlWrapper wrapper = new SqlWrapper();
+        wrapper.select().from("ec_prt_project").where().like("exam_id", 1L);
+        List<PrintingProject> list = jdbcTemplate.query(wrapper.build(), new BeanPropertyRowMapper(PrintingProject.class));
+        System.out.println(new JsonMapper().toJson(list));
+    }
+
 }