我在一个项目中使用JPA,该项目使用Spring Data和Hibernate的Criteria API。使用JpaSpecificationExecutor
我能够创建一些查询,让我可以使用Specification
在我的存储库中同时使用过滤和分页,只需调用Page<EventPost> findAll(Specification<EventPost> specification, Pageable pageable);
即可。
我现在遇到的问题是,我无法在没有hibernate的情况下对结果进行排序,从而产生像这样的无效查询:
select count(eventpost0_.event_id) as col_0_0_ from event_post eventpost0_ where eventpost0_.category_event_category_id=? order by eventpost0_.createDate desc
显然,Hibernate必须在发出真正的查找器查询之前对行进行计数,并错误地将我的Criteria中的order by子句添加到select count(*)
语句中。
这是我在日志中看到的逐字:
2016-09-05 09:22:36.987 [http-bio-8080-exec-4] DEBUG org.hibernate.SQL - select count(eventpost0_.event_id) as col_0_0_ from event_post eventpost0_ where eventpost0_.category_event_category_id=? order by eventpost0_.createDate desc
2016-09-05 09:22:36.991 [http-bio-8080-exec-4] WARN o.h.e.j.spi.SqlExceptionHelper - SQL Error: 0, SQLState: 42803
2016-09-05 09:22:36.992 [http-bio-8080-exec-4] ERROR o.h.e.j.spi.SqlExceptionHelper - ERROR: column "eventpost0_.createdate" must appear in the GROUP BY clause or be used in an aggregate function
Position: 133
这就是我创建查询的方式
@Override
public Predicate toPredicate(Root<EventPost> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Path<EventPost> category = root.get("category");
Path<Long> participants = root.get("participants");
Path<EventPostType> eventPostType = root.get("eventPostType");
final List<Predicate> predicates = new ArrayList<Predicate>();
if(criteria.getEventCategory()!=null){
predicates.add(cb.equal(category,criteria.getEventCategory()));
}
if(criteria.getParticipantsFrom()!=null){
predicates.add(cb.ge(participants,criteria.getParticipantsFrom()));
}else if(criteria.getParticipantsTo()!=null){
predicates.add(cb.lt(participants,criteria.getParticipantsTo()));
}
if(criteria.getEventPostType()!=null){
predicates.add(cb.equal(eventPostType,criteria.getEventPostType()));
}
query.orderBy(cb.desc(root.get("createDate")));
return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}
当我删除query.orderBy(cb.desc(root.get("createDate")));
时,一切正常。任何想法在这里可能有什么问题?
版本如下:
PostgreSQL Database 9.5.3.0 with PostGIS
spring-orm:jar:4.2.5.RELEASE
spring-data-jpa:jar:1.9.4.RELEASE
hibernate-spatial:jar:4.3:compile
hibernate-core:jar:4.3.11.Final:compile
postgresql:jar:8.4-701.jdbc4:compile
postgis-jdbc:jar:1.5.2:compile
答案 0 :(得分:0)
I have the following code which worked for me
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<T> cq = cb.createQuery(entity);
Root<T> root = cq.from(entity);
cq.orderBy(cb.desc(cb.sum(root.get(orderByString))));
// orderByString is string entity field that is being aggregated and which we want to put in orderby clause as well.