Example usage for javax.persistence.criteria CriteriaQuery having

List of usage examples for javax.persistence.criteria CriteriaQuery having

Introduction

In this page you can find the example usage for javax.persistence.criteria CriteriaQuery having.

Prototype

CriteriaQuery<T> having(Predicate... restrictions);

Source Link

Document

Specify restrictions over the groups of the query according the conjunction of the specified restriction predicates.

Usage

From source file:com.netflix.genie.web.data.repositories.jpa.specifications.JpaClusterSpecs.java

/**
 * Generate a specification given the parameters.
 *
 * @param name          The name of the cluster to find
 * @param statuses      The statuses of the clusters to find
 * @param tags          The tags of the clusters to find
 * @param minUpdateTime The minimum updated time of the clusters to find
 * @param maxUpdateTime The maximum updated time of the clusters to find
 * @return The specification//from   ww  w  .  ja va2  s  . c  om
 */
public static Specification<ClusterEntity> find(@Nullable final String name,
        @Nullable final Set<ClusterStatus> statuses, @Nullable final Set<TagEntity> tags,
        @Nullable final Instant minUpdateTime, @Nullable final Instant maxUpdateTime) {
    return (final Root<ClusterEntity> root, final CriteriaQuery<?> cq, final CriteriaBuilder cb) -> {
        final List<Predicate> predicates = new ArrayList<>();
        if (StringUtils.isNotBlank(name)) {
            predicates.add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb,
                    root.get(ClusterEntity_.name), name));
        }
        if (minUpdateTime != null) {
            predicates.add(cb.greaterThanOrEqualTo(root.get(ClusterEntity_.updated), minUpdateTime));
        }
        if (maxUpdateTime != null) {
            predicates.add(cb.lessThan(root.get(ClusterEntity_.updated), maxUpdateTime));
        }
        if (tags != null && !tags.isEmpty()) {
            final Join<ClusterEntity, TagEntity> tagEntityJoin = root.join(ClusterEntity_.tags);
            predicates.add(tagEntityJoin.in(tags));
            cq.groupBy(root.get(ClusterEntity_.id));
            cq.having(cb.equal(cb.count(root.get(ClusterEntity_.id)), tags.size()));
        }
        if (statuses != null && !statuses.isEmpty()) {
            //Could optimize this as we know size could use native array
            predicates.add(
                    cb.or(statuses.stream().map(status -> cb.equal(root.get(ClusterEntity_.status), status))
                            .toArray(Predicate[]::new)));
        }

        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    };
}

From source file:org.jdal.dao.jpa.JpaUtils.java

/**
 * Copy criteria without selection and order.
 * @param from source Criteria.//from   w  ww.  j av  a  2 s .co  m
 * @param to destination Criteria.
 */
private static void copyCriteriaWithoutSelectionAndOrder(CriteriaQuery<?> from, CriteriaQuery<?> to) {
    if (isEclipseLink(from) && from.getRestriction() != null) {
        // EclipseLink adds roots from predicate paths to critera. Skip copying 
        // roots as workaround.
    } else {
        // Copy Roots
        for (Root<?> root : from.getRoots()) {
            Root<?> dest = to.from(root.getJavaType());
            dest.alias(getOrCreateAlias(root));
            copyJoins(root, dest);
        }
    }

    to.groupBy(from.getGroupList());
    to.distinct(from.isDistinct());

    if (from.getGroupRestriction() != null)
        to.having(from.getGroupRestriction());

    Predicate predicate = from.getRestriction();
    if (predicate != null)
        to.where(predicate);
}

From source file:com.netflix.genie.web.data.repositories.jpa.specifications.JpaCommandSpecs.java

/**
 * Get a specification using the specified parameters.
 *
 * @param name     The name of the command
 * @param user     The name of the user who created the command
 * @param statuses The status of the command
 * @param tags     The set of tags to search the command for
 * @return A specification object used for querying
 *//*w w  w.  java  2 s .c om*/
public static Specification<CommandEntity> find(@Nullable final String name, @Nullable final String user,
        @Nullable final Set<CommandStatus> statuses, @Nullable final Set<TagEntity> tags) {
    return (final Root<CommandEntity> root, final CriteriaQuery<?> cq, final CriteriaBuilder cb) -> {
        final List<Predicate> predicates = new ArrayList<>();
        if (StringUtils.isNotBlank(name)) {
            predicates.add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb,
                    root.get(CommandEntity_.name), name));
        }
        if (StringUtils.isNotBlank(user)) {
            predicates.add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb,
                    root.get(CommandEntity_.user), user));
        }
        if (statuses != null && !statuses.isEmpty()) {
            predicates.add(
                    cb.or(statuses.stream().map(status -> cb.equal(root.get(CommandEntity_.status), status))
                            .toArray(Predicate[]::new)));
        }
        if (tags != null && !tags.isEmpty()) {
            final Join<CommandEntity, TagEntity> tagEntityJoin = root.join(CommandEntity_.tags);
            predicates.add(tagEntityJoin.in(tags));
            cq.groupBy(root.get(CommandEntity_.id));
            cq.having(cb.equal(cb.count(root.get(CommandEntity_.id)), tags.size()));
        }
        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    };
}

From source file:com.netflix.genie.web.data.repositories.jpa.specifications.JpaApplicationSpecs.java

/**
 * Get a specification using the specified parameters.
 *
 * @param name     The name of the application
 * @param user     The name of the user who created the application
 * @param statuses The status of the application
 * @param tags     The set of tags to search with
 * @param type     The type of applications to fine
 * @return A specification object used for querying
 *///from   w w w  .  ja v  a  2 s  . c om
public static Specification<ApplicationEntity> find(@Nullable final String name, @Nullable final String user,
        @Nullable final Set<ApplicationStatus> statuses, @Nullable final Set<TagEntity> tags,
        @Nullable final String type) {
    return (final Root<ApplicationEntity> root, final CriteriaQuery<?> cq, final CriteriaBuilder cb) -> {
        final List<Predicate> predicates = new ArrayList<>();
        if (StringUtils.isNotBlank(name)) {
            predicates.add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb,
                    root.get(ApplicationEntity_.name), name));
        }
        if (StringUtils.isNotBlank(user)) {
            predicates.add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb,
                    root.get(ApplicationEntity_.user), user));
        }
        if (statuses != null && !statuses.isEmpty()) {
            predicates.add(
                    cb.or(statuses.stream().map(status -> cb.equal(root.get(ApplicationEntity_.status), status))
                            .toArray(Predicate[]::new)));
        }
        if (tags != null && !tags.isEmpty()) {
            final Join<ApplicationEntity, TagEntity> tagEntityJoin = root.join(ApplicationEntity_.tags);
            predicates.add(tagEntityJoin.in(tags));
            cq.groupBy(root.get(ApplicationEntity_.id));
            cq.having(cb.equal(cb.count(root.get(ApplicationEntity_.id)), tags.size()));
        }
        if (StringUtils.isNotBlank(type)) {
            predicates.add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb,
                    root.get(ApplicationEntity_.type), type));
        }
        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    };
}

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

protected Long count(CriteriaQuery<T> criteriaQuery, List<Filter> filters) {
    Assert.notNull(criteriaQuery);//from   w  w  w.  ja v a 2  s.  c om
    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:net.groupbuy.dao.impl.BaseDaoImpl.java

protected Long count(CriteriaQuery<T> criteriaQuery, List<Filter> filters) {
    Assert.notNull(criteriaQuery);/*from ww w .  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));

    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:de.hopmann.msc.slave.service.PackageInstallationBean.java

public PackageInstallationEntity getInstallationEntity(PackageResolved packageModel,
        Set<PackageInstallationEntity> requiredDependencies, PackageInstallerHolder packageInstallerHolder) {
    try {/*w ww .j av a2s  .  c om*/

        // TODO repository version, flavor, etc.

        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery<PackageInstallationEntity> query = cb.createQuery(PackageInstallationEntity.class);
        Root<PackageInstallationEntity> p = query.from(PackageInstallationEntity.class);
        Path<PackageInstallerEntity> pInstaller = p.get(PackageInstallationEntity_.packageInstaller);

        List<Predicate> predicates = new ArrayList<Predicate>();

        predicates.add(cb.equal(p.get(PackageInstallationEntity_.packageName), packageModel.getPackageName()));
        predicates.add(cb.equal(p.get(PackageInstallationEntity_.sourceVersion).get(Version_.versionNumber),
                packageModel.getPackageAccessor().getSourceVersion().getVersionNumber()));

        predicates.add(cb.between(pInstaller.get(PackageInstallerEntity_.version).get(Version_.versionNumber),
                packageInstallerHolder.getDependencyMinVersion(),
                packageInstallerHolder.getDependencyMaxVersion()));

        // TODO flavor arch

        if (requiredDependencies.isEmpty()) {
            query.where(cb.and(predicates.toArray(new Predicate[] {})));
        } else {
            SetJoin<PackageInstallationEntity, PackageInstallationEntity> join = p
                    .join(PackageInstallationEntity_.actualDependencies);

            predicates.add(join.in(requiredDependencies));

            // Expression<Set<PackageInstallationEntity>> pDependencies = p
            // .get(PackageInstallationEntity_.actualDependencies);
            // predicates.add(pDependencies.in(requiredDependencies));

            query.where(cb.and(predicates.toArray(new Predicate[] {})));
            Path<Long> pId = p.get(PackageInstallationEntity_.id);
            query.groupBy(pId);
            query.having(cb.ge(cb.count(pId), requiredDependencies.size()));
            query.distinct(true);
        }

        return entityManager.createQuery(query).getSingleResult();
    } catch (NoResultException e) {
        return null;
    }
}

From source file:org.agric.oxm.utils.JpaUtils.java

/**
 * Copy Criteria without Selection/*from  w ww.j a v a 2s . c  om*/
 * 
 * @param from
 *            source Criteria
 * @param to
 *            destination Criteria
 */
public static void copyCriteriaNoSelection(CriteriaQuery<?> from, CriteriaQuery<?> to) {

    // Copy Roots
    for (Root<?> root : from.getRoots()) {
        Root<?> dest = to.from(root.getJavaType());
        dest.alias(getOrCreateAlias(root));
        copyJoins(root, dest);
    }

    to.groupBy(from.getGroupList());
    to.distinct(from.isDistinct());
    to.having(from.getGroupRestriction());
    to.where(from.getRestriction());
    to.orderBy(from.getOrderList());
}

From source file:org.easy.criteria.CriteriaProcessor.java

/**
 * Finds all the tuples for the given criteria. Make sure you have provided
 * columns information in CriteriaContainer that you want in this tuple
 * result-set.//  w  w  w. j  a  va  2 s  . c  o m
 * 
 * @param criteria
 *            - Criteria that you want to apply to this search.
 * @param distinct
 *            -
 * @param startIndex
 *            - Pass 0 or less to disable paging.
 * @param maxResult
 *            - Pass 0 or less to disable paging.
 * @param lockMode
 *            - Pass NULL if your are not managing transaction.
 *            LockModeType.NONE will through exception if no transaction is
 *            active.
 * @return - A list of tuples or an empty list if no result were found.
 */
public <T> List<Tuple> findAllTuple(CriteriaComposer<T> criteria, boolean distinct,
        QueryProperties properties) {

    log.trace("CriteriaProcessor.findAllTuple");

    Preconditions.checkNotNull(criteria);

    Class<T> forClass = criteria.getEntityClass();
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteriaQuery = criteriaBuilder.createQuery(Tuple.class);

    log.debug("root =" + forClass.getName());
    Root<T> root = criteriaQuery.from(forClass);

    List<Predicate> wherePredicates = new ArrayList<Predicate>();
    List<Selection<?>> selectPredicates = new ArrayList<Selection<?>>();
    Map<Integer, Order> orderByPredicates = new HashMap<Integer, Order>(0);
    Map<Integer, Expression<?>> groupByPredicates = new HashMap<Integer, Expression<?>>(0);
    List<Predicate> havingPredicates = new ArrayList<Predicate>(0);

    if (criteria != null) {
        criteria.generateJoins(root);
        criteria.generateSelect(criteriaBuilder, selectPredicates);
        criteria.generateGroupBy(criteriaBuilder, groupByPredicates);
        criteria.generateWhere(criteriaBuilder, wherePredicates);
        criteria.generateOrderBy(criteriaBuilder, orderByPredicates);
        criteria.generateHaving(criteriaBuilder, havingPredicates);
    }

    Preconditions.checkState(selectPredicates != null);
    Preconditions.checkArgument(selectPredicates.size() > 0, "No column name found for select clause. "
            + "Atleast one should be provided for Tuple result. Consider using findAllEntity instead.");

    criteriaQuery.multiselect(selectPredicates);

    criteriaQuery.where(wherePredicates.toArray(new Predicate[wherePredicates.size()]));

    if (orderByPredicates != null && orderByPredicates.size() > 0) {
        Order[] orderByList = new Order[orderByPredicates.size()];
        orderByPredicates.values().toArray(orderByList);
        criteriaQuery.orderBy(orderByList);
    }

    if (groupByPredicates != null && groupByPredicates.size() > 0) {
        Expression<?>[] groupByList = new Expression<?>[groupByPredicates.size()];
        groupByPredicates.values().toArray(groupByList);
        criteriaQuery.groupBy(groupByList);
    }

    criteriaQuery.having(havingPredicates.toArray(new Predicate[havingPredicates.size()]));

    TypedQuery<Tuple> query = entityManager.createQuery(criteriaQuery);

    if (properties != null)
        properties.applyProperties(query);

    List<Tuple> tuples = query.getResultList();

    if (tuples == null)
        tuples = new ArrayList<Tuple>(0);

    log.debug("CriteriaProcessor.findAllEntity result size=" + tuples.size());

    return tuples;
}

From source file:org.jboss.pressgang.ccms.filter.utils.JPAUtils.java

/**
 * Copy Criteria without Selection/*w  w  w.  j  ava 2s  .  c o  m*/
 *
 * @param from source Criteria
 * @param to   destination Criteria
 */
public static void copyCriteriaNoSelection(CriteriaQuery<?> from, CriteriaQuery<?> to) {

    // Copy Roots
    for (Root<?> root : from.getRoots()) {
        Root<?> dest = to.from(root.getJavaType());
        dest.alias(getOrCreateAlias(root));
        copyJoins(root, dest);
    }

    if (from.getGroupList() != null)
        to.groupBy(from.getGroupList());
    to.distinct(from.isDistinct());
    if (from.getGroupRestriction() != null)
        to.having(from.getGroupRestriction());
    if (from.getRestriction() != null)
        to.where(from.getRestriction());
    if (from.getOrderList() != null)
        to.orderBy(from.getOrderList());
}