Spring 带有 QueryDSL 的数据 JPA,聚合函数的计数问题
Spring Data JPA with QueryDSL, Count issue with aggregate function
我正在将 Spring Data JPA 与 QueryDSL 一起使用,并尝试在 where 条件下使用 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
中也不起作用,因为求和函数不能与 where 条件下的计数一起使用。当我必须先计数然后获取真实数据时,我不知道如何处理此类问题。
有人可以帮我解决 JPA
处理此类问题的方法吗?
请不要建议 @Query
注释,因为我无法使用它。由于动态过滤要求。
您正在使用聚合函数 (sum)。然后你需要 having() 而不是 where()
这个例子真的很大。你只需要关心分页和拥有元素。
如果你有不同的谓词和一个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);
编辑 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));
我正在将 Spring Data JPA 与 QueryDSL 一起使用,并尝试在 where 条件下使用 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
中也不起作用,因为求和函数不能与 where 条件下的计数一起使用。当我必须先计数然后获取真实数据时,我不知道如何处理此类问题。
有人可以帮我解决 JPA
处理此类问题的方法吗?
请不要建议 @Query
注释,因为我无法使用它。由于动态过滤要求。
您正在使用聚合函数 (sum)。然后你需要 having() 而不是 where()
这个例子真的很大。你只需要关心分页和拥有元素。
如果你有不同的谓词和一个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);
编辑 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));