我正在使用QueryDSL的Spring Data JPA,并试图在其中的条件下使用Sum函数,因为我正在使用分页,所以我必须首先获得计数。所以我有java代码如下:-
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
中也不能工作,因为sum函数不能在where条件下与count一起使用。我不知道如何处理这样的问题,当我必须先得到计数,然后获取真正的数据。有谁能帮我说说JPA
是怎么处理这个问题的吗?
请不要建议@Query
注释,因为我不能使用它。由于动态过滤要求
您正在使用聚合函数(sum)。那么你需要用()来代替()
这个例子真的很大。您只需要关心分页和拥有元素。
如果你有不同的谓词和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));