Example usage for javax.persistence.criteria CriteriaBuilder count

List of usage examples for javax.persistence.criteria CriteriaBuilder count

Introduction

In this page you can find the example usage for javax.persistence.criteria CriteriaBuilder count.

Prototype

Expression<Long> count(Expression<?> x);

Source Link

Document

Create an aggregate expression applying the count operation.

Usage

From source file:com.uni.dao.etc.UniJpaRepository.java

/**
 * Creates a new count query for the given {@link Specification}.
 * /*from  ww  w .  j  av a 2 s . c  o  m*/
 * @param spec can be {@literal null}.
 * @return
 */
private TypedQuery<Long> getCountQuery(Specification<T> spec) {

    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Long> query = builder.createQuery(Long.class);

    Root<T> root = applySpecificationToCriteria(spec, query);
    query.select(builder.count(root));

    return em.createQuery(query);
}

From source file:org.querybyexample.jpa.GenericRepository.java

/**
 * Count the number of E instances./*w  w w  .  j  av  a  2s.  c o  m*/
 *
 * @param entity a sample entity whose non-null properties may be used as
 * search hint
 * @param searchParameters carries additional search information
 * @return the number of entities matching the search.
 */
@Transactional(readOnly = true)
public int findCount(E entity, SearchParameters sp) {
    checkNotNull(entity, "The entity cannot be null");
    checkNotNull(sp, "The searchParameters cannot be null");

    if (sp.hasNamedQuery()) {
        return byNamedQueryUtil.numberByNamedQuery(sp).intValue();
    }
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();

    CriteriaQuery<Long> criteriaQuery = builder.createQuery(Long.class);
    Root<E> root = criteriaQuery.from(type);

    if (sp.getDistinct()) {
        criteriaQuery = criteriaQuery.select(builder.countDistinct(root));
    } else {
        criteriaQuery = criteriaQuery.select(builder.count(root));
    }

    // predicate
    Predicate predicate = getPredicate(root, builder, entity, sp);
    if (predicate != null) {
        criteriaQuery = criteriaQuery.where(predicate);
    }

    orderByUtil.forceJoinOrder(root, sp);

    TypedQuery<Long> typedQuery = entityManager.createQuery(criteriaQuery);

    applyCacheHints(typedQuery, sp);
    Long count = typedQuery.getSingleResult();

    if (count != null) {
        return count.intValue();
    } else {
        log.warn("findCount returned null");
        return 0;
    }
}

From source file:com.zero.dao.impl.BaseDaoImpl.java

protected Long count(CriteriaQuery<T> criteriaQuery, List<Filter> filters) {
    Assert.notNull(criteriaQuery);//from  www  .  j a  v  a2  s. c o m
    Assert.notNull(criteriaQuery.getSelection());
    Assert.notEmpty(criteriaQuery.getRoots());

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    addRestrictions(criteriaQuery, filters);

    CriteriaQuery<Long> countCriteriaQuery = criteriaBuilder.createQuery(Long.class);

    for (Root<?> root : criteriaQuery.getRoots()) {
        Root<?> dest = countCriteriaQuery.from(root.getJavaType());
        dest.alias(getAlias(root));
        copyJoins(root, dest);
    }

    Root<?> countRoot = getRoot(countCriteriaQuery, criteriaQuery.getResultType());
    countCriteriaQuery.select(criteriaBuilder.count(countRoot.get("id").<String>get("stcd")));

    if (criteriaQuery.getGroupList() != null) {
        countCriteriaQuery.groupBy(criteriaQuery.getGroupList());
    }
    if (criteriaQuery.getGroupRestriction() != null) {
        countCriteriaQuery.having(criteriaQuery.getGroupRestriction());
    }
    if (criteriaQuery.getRestriction() != null) {
        countCriteriaQuery.where(criteriaQuery.getRestriction());
    }
    return entityManager.createQuery(countCriteriaQuery).setFlushMode(FlushModeType.COMMIT).getSingleResult();
}

From source file:com.netflix.genie.core.jpa.services.JpaJobSearchServiceImpl.java

/**
 * {@inheritDoc}//w  ww .  j  ava 2s.  c  om
 */
@Override
public Page<JobSearchResult> findJobs(final String id, final String jobName, final String user,
        final Set<JobStatus> statuses, final Set<String> tags, final String clusterName, final String clusterId,
        final String commandName, final String commandId, final Date minStarted, final Date maxStarted,
        final Date minFinished, final Date maxFinished, @NotNull final Pageable page) {
    log.debug("called");

    final CriteriaBuilder cb = this.entityManager.getCriteriaBuilder();
    final CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
    final Root<JobEntity> root = countQuery.from(JobEntity.class);

    final Predicate whereClause = JpaJobSpecs.getFindPredicate(root, cb, id, jobName, user, statuses, tags,
            clusterName, clusterId == null ? null : this.clusterRepository.findOne(clusterId), commandName,
            commandId == null ? null : this.commandRepository.findOne(commandId), minStarted, maxStarted,
            minFinished, maxFinished);

    countQuery.select(cb.count(root)).where(whereClause);

    final Long count = this.entityManager.createQuery(countQuery).getSingleResult();

    // Use the count to make sure we even need to make this query
    if (count > 0) {
        final CriteriaQuery<JobSearchResult> contentQuery = cb.createQuery(JobSearchResult.class);
        contentQuery.from(JobEntity.class);

        contentQuery.multiselect(root.get(JobEntity_.id), root.get(JobEntity_.name), root.get(JobEntity_.user),
                root.get(JobEntity_.status), root.get(JobEntity_.started), root.get(JobEntity_.finished),
                root.get(JobEntity_.clusterName), root.get(JobEntity_.commandName));

        contentQuery.where(whereClause);

        final Sort sort = page.getSort();
        final List<Order> orders = new ArrayList<>();
        sort.iterator().forEachRemaining(order -> {
            if (order.isAscending()) {
                orders.add(cb.asc(root.get(order.getProperty())));
            } else {
                orders.add(cb.desc(root.get(order.getProperty())));
            }
        });

        contentQuery.orderBy(orders);

        final List<JobSearchResult> results = this.entityManager.createQuery(contentQuery)
                .setFirstResult(page.getOffset()).setMaxResults(page.getPageSize()).getResultList();

        return new PageImpl<>(results, page, count);
    } else {
        return new PageImpl<>(Lists.newArrayList(), page, count);
    }
}

From source file:net.groupbuy.dao.impl.BaseDaoImpl.java

protected Long count(CriteriaQuery<T> criteriaQuery, List<Filter> filters) {
    Assert.notNull(criteriaQuery);// w  w w  .ja  va 2 s.  c  o m
    Assert.notNull(criteriaQuery.getSelection());
    Assert.notEmpty(criteriaQuery.getRoots());

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    addRestrictions(criteriaQuery, filters);

    CriteriaQuery<Long> countCriteriaQuery = criteriaBuilder.createQuery(Long.class);
    for (Root<?> root : criteriaQuery.getRoots()) {
        Root<?> dest = countCriteriaQuery.from(root.getJavaType());
        dest.alias(getAlias(root));
        copyJoins(root, dest);
    }

    Root<?> countRoot = getRoot(countCriteriaQuery, criteriaQuery.getResultType());
    countCriteriaQuery.select(criteriaBuilder.count(countRoot));

    if (criteriaQuery.getGroupList() != null) {
        countCriteriaQuery.groupBy(criteriaQuery.getGroupList());
    }
    if (criteriaQuery.getGroupRestriction() != null) {
        countCriteriaQuery.having(criteriaQuery.getGroupRestriction());
    }
    if (criteriaQuery.getRestriction() != null) {
        countCriteriaQuery.where(criteriaQuery.getRestriction());
    }
    return entityManager.createQuery(countCriteriaQuery).setFlushMode(FlushModeType.COMMIT).getSingleResult();
}

From source file:hr.diskobolos.persistence.impl.EvaluationAnswerPersistenceImpl.java

@Override
public Long fetchNumberOfMemberRegistersWithoutTerms() {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Long> cq = cb.createQuery(Long.class);
    Root<MemberRegister> memberRegister = cq.from(MemberRegister.class);
    Subquery<Long> sq = cq.subquery(Long.class);
    Root<EvaluationAnswer> evaluationAnswer = sq.from(EvaluationAnswer.class);
    Join<EvaluationAnswer, QuestionChoicesDef> choiceDef = evaluationAnswer.join(EvaluationAnswer_.answer);
    Join<QuestionChoicesDef, EvaluationQuestionDef> questionDef = choiceDef
            .join(QuestionChoicesDef_.evaluationQuestionDef);
    ParameterExpression<QuestionnaireType> questionnaireType = cb.parameter(QuestionnaireType.class,
            "questionnaireType");
    sq.select(evaluationAnswer.get("memberRegister").get("id"))
            .where(cb.equal(questionDef.get(EvaluationQuestionDef_.questionnaireType), questionnaireType));
    cq.select(cb.count(memberRegister.get("id"))).where(cb.not(cb.in(memberRegister.get("id")).value(sq)));
    TypedQuery<Long> query = entityManager.createQuery(cq);
    query.setParameter("questionnaireType", QuestionnaireType.TERMS_OF_CONDITION);
    return query.getSingleResult();
}

From source file:it.attocchi.jpa2.JpaController.java

public <T extends Serializable> int getItemCount(Class<T> classObj) throws Exception {
    int returnValue = 0;

    EntityManager em = getEntityManager();

    try {//w  w  w . j a v a  2s .c  o m

        // StringBuffer hsqlQuery = new StringBuffer();
        // hsqlQuery.append("select count(*) from ");
        // hsqlQuery.append(classObj.getCanonicalName());
        // hsqlQuery.append(" as o");
        // Query q = em.createQuery(hsqlQuery.toString());
        //
        // returnValue = ((Long) q.getSingleResult()).intValue();

        CriteriaBuilder qb = em.getCriteriaBuilder();
        CriteriaQuery<Long> cq = qb.createQuery(Long.class);
        cq.select(qb.count(cq.from(classObj)));

        Long res = em.createQuery(cq).getSingleResult();

        return res.intValue();

    } catch (Exception e) {
        throw e;
    } finally {
        // Close the database connection:
        if (!globalTransactionOpen) {
            // if (em.getTransaction().isActive())
            // em.getTransaction().rollback();
            closeEm(); // em.close();
        }
    }

}

From source file:it.attocchi.jpa2.JpaController.java

public <T extends Serializable> Long countBy(Class<T> clazz, JPAEntityFilter<T> filter) throws Exception {
    Long res = 0L;//  ww  w. j  av a2  s  . com

    testClazz(clazz);

    EntityManager em = getEntityManager();

    try {

        if (filter != null) {

            // Source:
            // http://stackoverflow.com/questions/5349264/total-row-count-for-pagination-using-jpa-criteria-api

            CriteriaQuery<T> cq = filter.getCriteria(clazz, getEmf());

            // TypedQuery<T> q = em.createQuery(cq);
            //
            // q.setFirstResult(filter.getLimit() * filter.getPageNumber());
            // q.setMaxResults(filter.getLimit());
            //
            // res = Long.valueOf(q.getResultList().size());

            // CriteriaBuilder qb = em.getCriteriaBuilder();
            // CriteriaQuery<Long> countQuery = qb.createQuery(Long.class);
            // countQuery.select(qb.count(cq.from(clazz)));
            // // cq.where(/*your stuff*/);
            // return em.createQuery(cq).getSingleResult();

            CriteriaBuilder builder = em.getCriteriaBuilder();
            CriteriaQuery<Long> cqCount = builder.createQuery(Long.class);
            cqCount.select(builder.count(cqCount.from(clazz)));

            // Following line if commented causes
            // [org.hibernate.hql.ast.QuerySyntaxException: Invalid path:
            // 'generatedAlias1.enabled' [select count(generatedAlias0) from
            // xxx.yyy.zzz.Brand as generatedAlias0 where (
            // generatedAlias1.enabled=:param0 ) and (
            // lower(generatedAlias1.description) like :param1 )]]
            em.createQuery(cqCount);

            // filter.getCriteria(clazz, getEmf());
            cqCount.where(filter.getWherePredicate(clazz, getEmf()));

            res = em.createQuery(cqCount).getSingleResult();

        } else {
            // res = findAll(clazz);

            CriteriaBuilder qb = em.getCriteriaBuilder();
            CriteriaQuery<Long> cq = qb.createQuery(Long.class);
            cq.select(qb.count(cq.from(clazz)));
            // cq.where(/*your stuff*/);
            res = em.createQuery(cq).getSingleResult();

        }

    } catch (Exception e) {
        throw e;
    } finally {
        // Close the database connection:
        if (!globalTransactionOpen) {
            // if (em.getTransaction().isActive())
            // em.getTransaction().rollback();
            closeEm(); // em.close();
        }
    }

    return res;
}

From source file:com.tasktop.c2c.server.profile.tests.service.BaseProfileServiceTest.java

private <T> int getEntityCount(Class<T> entityClass) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Long> query = criteriaBuilder.createQuery(Long.class);
    Root<T> root = query.from(entityClass);
    query.select(criteriaBuilder.count(root));
    return entityManager.createQuery(query).getSingleResult().intValue();
}