JpaSpecificationExecutor :具有规范的复杂查询 [英] JpaSpecificationExecutor : complex queries with specifications
问题描述
我实际上是在使用不同的过滤器进行研究.
I'm actually creating research with different filters.
当我使用 JpaRepository 进行简单查询时,我发现 JpaSpecificationExecutor 可以使用 Criterias 进行动态查询.
As I'm using the JpaRepository to make simple queries, I found the JpaSpecificationExecutor to make dynamic queries with the Criterias.
我的问题是我需要使用 group by 和 count() 创建一个复杂的查询.对于 group by 来说没问题,但我不知道如何覆盖select"部分以放置count"指令.
My problem is I need to create a complex query with a group by and a count(). It's ok for the group by but I don't find how I can overide the "select" part to put a "count" instruction.
有人可以帮我吗?
我使用的是 spring 3.1.2 和 spring-jpa-data 1.0.3这是我的代码:
I'm using spring 3.1.2 and spring-jpa-data 1.0.3 Here is my code :
return new Specification< Article >() {
@Override
public Predicate toPredicate(final Root<Article> root,
final CriteriaQuery<?> query, final CriteriaBuilder builder) {
//count ???
query.groupBy(root.get(Article_.id));
Predicate p = builder.and(builder.like(root.<String> get(Article_.title), "%" + title + "%"));
return p;
}
}
谢谢!
推荐答案
不幸的是,你不能用 spring-data 规范来做到这一点.
Unfortunately you cannot do this with spring-data Specification.
你可以看到为什么和如何做到这一点,同时仍然在这里使用 spring-data(有一个简单的查询只返回一个字段):spring-data 规范 - 返回 id 列表而不是对象
You can see why and how to do it while still using spring-data here(there is a simple query returning just one field): spring-data specifications - return list of ids instead of objects
要获取字段列表,您可以使用 JPA 元组.你可以在这里找到一个例子:JPA &Criteria API - 仅选择特定列
To get a list of fields you can use JPA Tuple. You can find an example here: JPA & Criteria API - Select only specific columns
短版:您需要创建一个自定义 spring-data 存储库,该存储库将使用 CriteriaQuery
.
Short version: You need to create a custom spring-data repository which will use CriteriaQuery<Tuple>
.
这篇关于JpaSpecificationExecutor :具有规范的复杂查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!