2016-08-16 414 views
0

我在QueryDSL中使用Spring Data JPA,並試圖在where條件中使用Sum函數,因爲我使用分頁,所以我必須先計數。 所以我有一個像下面的Java代碼: -帶有QueryDSL的Spring Data JPA,帶聚合函數的Count問題

NumberPath<Double> path = entityPath.getNumber("qty", Double.class); 
BooleanExpression exp = path.sum().loe(120);   
JPQLQuery countQuery = from(stock).where(exp); 
long count = countQuery.count(); 

其創建這樣的查詢: -

select count(stock0_.stock_id) as col_0_0_ from stock stock0_ 
where sum(stock0_.qty)>=120; 

和我收到Error Code: 1111. Invalid use of group function

以上查詢不在SQL以及因爲和功能不能用於計數在哪裏條件。我不知道如何處理這樣的問題,當我必須先計算並獲取真實數據。 有人可以幫我解決這個問題的方法是什麼JPA

請不要建議@Query註釋,因爲我不能使用它。由於動態過濾的要求。

回答

1

您正在使用聚合函數(總和)。那麼你需要有()而不是()

這個例子是一個非常大的例子。你只需要關心分頁和元素。

如果你有不同的謂詞pageRequest對象。

頁面請求例如:

pageRequest = new PageRequest(
       MI_PAGE, 
       LIMIT, 
       Sort.Direction.valueOf(ASC), 
       ORDER_FIELD); 

EntityQ表示QueryDSL生成元實體。

查詢例如:

new JPAQuery(em).from(entityQ).where(entityQ.id.in(

     new JPASubQuery() 
     .from(entity2Q).innerJoin(entity2Q.objEntityQ, entityQ) 
      .where(ENTITY, PREDICATE)       
      .groupBy(entity2Q.objEntityQ.id) 
      .having(Wildcard.count.goe(SIZE))     
     .list(entity2Q.objEntityQ.id) 

    )) 
    .offset(pageRequest.getOffset()) 
    .limit(pageRequest.getPageSize()) 
    .orderBy(ORDERS).list(entityQ); 

EDIT 2更具體的爲你的榜樣

我通常在我的自定義存儲庫持久化上下文:

@PersistenceContext 
EntityManager em 

然後,你可以創建一個簡單的JPAQuery:

new JPAQuery(em) 
.from(YOUR_STOCK_QUERYDSL_ENTITY) 
.groupBy(YOUR_STOCK_QUERYDSL_ENTITY.field_to_sum) 
.having(YOUR_STOCK_QUERYDSL_ENTITY.field_to_sum.sum().as("alias") 
.goe(100)); 
+0

不,我不使用組函數 –

+0

其中sum(stock0_.qty)> = 120是一個組函數。這應該使用having()比較或使用JPASubquery。 – crm86

+0

能否請你詳細解釋一下或提供任何鏈接。如何通過配頁使用 –