21

I would like to do this but with the criteria API instead:

select count(distinct e) from Event e, IN(e.userAccessPermissions) p where p.principal = :principal and p.permission in (:permissions)

Any ideas?

Piotr
  • 4,813
  • 7
  • 35
  • 46

4 Answers4

47

You can use countDistinct on CriteriaBuilder

criteriaQuery.select(criteriaBuilder.countDistinct(entityRoot))
Jakub Kahovec
  • 582
  • 5
  • 5
0
    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();


    }

With Spring Data Jpa, we can use this method:

     /*
     * (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()));
    }
kafkas
  • 475
  • 1
  • 4
  • 11
0

Use c.distinct(true) on your Query.

See http://relation.to/Bloggers/ATypesafeCriteriaQueryAPIForJPA for more samples.

ddewaele
  • 22,363
  • 10
  • 69
  • 82
  • 1
    I would appreciate it if you could provide me with an example of how to do it in my particular case, because Ive used distinct in the criteria api but for some reason this use case does not work for me. – Piotr Jun 01 '11 at 08:32
0

Like this?

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"));
Stijn Geukens
  • 15,454
  • 8
  • 66
  • 101