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:org.xlcloud.service.dao.JpaVirtualClusterDefinitionsDao.java

/** {@inheritDoc} */
@Override//from w  w w .j  a  va2 s .c  o  m
public List<VirtualClusterDefinitionModel> findByTypeAndTags(Long accountId, String type, Set<String> tags,
        boolean paged) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("finding vc definitions with type id: " + type + " and following tag ids:"
                + ToStringBuilder.reflectionToString(tags));
    }

    CriteriaBuilder criteriaBuilder = getCriteriaBuilder();
    CriteriaQuery<Tuple> query = criteriaBuilder.createTupleQuery();
    Root<VirtualClusterDefinitionModel> vcDefRoot = query.from(VirtualClusterDefinitionModel.class);

    Predicate typePredicate = criteriaBuilder.equal(vcDefRoot.get(VirtualClusterDefinitionModel_.type), type);
    Predicate tagsPredicate = vcDefRoot.get(VirtualClusterDefinitionModel_.tags).in(tags);

    boolean skipTagsJoin = tags.isEmpty();
    Predicate predicate = skipTagsJoin ? typePredicate : criteriaBuilder.and(typePredicate, tagsPredicate);

    Predicate scopePredicate;
    if (accountId != null) {
        Predicate accountPredicate = criteriaBuilder
                .equal(vcDefRoot.get(VirtualClusterDefinitionModel_.accountId), accountId);
        Predicate privatePredicate = criteriaBuilder
                .equal(vcDefRoot.get(VirtualClusterDefinitionModel_.catalogScope), CatalogScope.PRIVATE);
        scopePredicate = criteriaBuilder.and(accountPredicate, privatePredicate);
    } else {
        scopePredicate = criteriaBuilder.equal(vcDefRoot.get(VirtualClusterDefinitionModel_.catalogScope),
                CatalogScope.PUBLIC);
    }

    predicate = criteriaBuilder.and(predicate, scopePredicate);

    query.multiselect(vcDefRoot, criteriaBuilder.count(vcDefRoot));
    query.where(predicate);
    query.groupBy(vcDefRoot);
    if (!skipTagsJoin) {
        query.having(criteriaBuilder.equal(criteriaBuilder.count(vcDefRoot), tags.size()));
    }

    List<Tuple> list = getResultList(query, vcDefRoot, paged);
    List<VirtualClusterDefinitionModel> results = new LinkedList<VirtualClusterDefinitionModel>();
    for (Tuple t : list) {
        results.add((VirtualClusterDefinitionModel) t.get(0));
    }
    return results;
}