我想使用条件API来完成这个操作:
select count(distinct e) from Event e, IN(e.userAccessPermissions) p where p.principal = :principal and p.permission in (:permissions)
任何想法?我想使用条件API来完成这个操作:
select count(distinct e) from Event e, IN(e.userAccessPermissions) p where p.principal = :principal and p.permission in (:permissions)
任何想法?你可以在CriteriaBuilder中使用countDistinct。
criteriaQuery.select(criteriaBuilder.countDistinct(entityRoot))
像这样吗?
Criteria crit = session.createCriteria(Event.class):
crit.createAlias("userAccessPermissions", "p");
crit.add(Restrictions.eq("p.principal", principal);
crit.add(Restrictions.in("p.permission", permissions);
crit.setProjection(Projections.countDistinct("id"));
在您的查询中使用c.distinct(true)。
请参阅http://relation.to/Bloggers/ATypesafeCriteriaQueryAPIForJPA以获取更多示例。
public long getCount(String xValue){
EntityManager entityManager = this.getEntityManager();
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> criteriaQuery = cb.createQuery(Long.class);
Root<MyEntity> root = criteriaQuery.from(MyEntity.class);
criteriaQuery.select(cb.count(criteriaQuery.from(MyEntity.class)));
List<Predicate> predicates = new ArrayList<>();
Predicate xEquals = cb.equal(root.get("x"), xValue);
predicates.add(xEquals);
criteriaQuery.select(cb.countDistinct(root));
criteriaQuery.where(predicates.toArray(new Predicate[0]));
return entityManager.createQuery(criteriaQuery).getSingleResult();
}
使用Spring Data Jpa,我们可以使用这个方法:
/*
* (non-Javadoc)
* @see org.springframework.data.jpa.repository.JpaSpecificationExecutor#count(org.springframework.data.jpa.domain.Specification)
*/
@Override
public long count(@Nullable Specification<T> spec) {
return executeCountQuery(getCountQuery(spec, getDomainClass()));
}