How to do a distinct count in JPA critera API?

后端 未结 4 1486
盖世英雄少女心
盖世英雄少女心 2021-02-13 10:14

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 an         


        
4条回答
  •  逝去的感伤
    2021-02-13 10:46

        public long getCount(String xValue){
          EntityManager entityManager = this.getEntityManager();
    
          CriteriaBuilder cb = entityManager.getCriteriaBuilder();
          CriteriaQuery criteriaQuery = cb.createQuery(Long.class);
          Root root = criteriaQuery.from(MyEntity.class);
    
          criteriaQuery.select(cb.count(criteriaQuery.from(MyEntity.class)));
    
          List 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 spec) {
            return executeCountQuery(getCountQuery(spec, getDomainClass()));
        }
    

提交回复
热议问题