Example usage for javax.persistence.criteria CriteriaQuery where

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

Introduction

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

Prototype

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

Source Link

Document

Modify the query to restrict the query result according to the conjunction of the specified restriction predicates.

Usage

From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java

private void addPredicateHas(List<List<? extends IQueryParameterType>> theHasParameters,
        DateRangeParam theLastUpdated) {

    for (List<? extends IQueryParameterType> nextOrList : theHasParameters) {

        StringBuilder valueBuilder = new StringBuilder();
        String targetResourceType = null;
        String owningParameter = null;
        String parameterName = null;
        for (IQueryParameterType nextParam : nextOrList) {
            HasParam next = (HasParam) nextParam;
            if (valueBuilder.length() > 0) {
                valueBuilder.append(',');
            }//w ww.ja va2s. c o  m
            valueBuilder.append(UrlUtil.escape(next.getValueAsQueryToken(myContext)));
            targetResourceType = next.getTargetResourceType();
            owningParameter = next.getOwningFieldName();
            parameterName = next.getParameterName();
        }

        if (valueBuilder.length() == 0) {
            continue;
        }

        String matchUrl = targetResourceType + '?' + UrlUtil.escape(parameterName) + '='
                + valueBuilder.toString();
        RuntimeResourceDefinition targetResourceDefinition;
        try {
            targetResourceDefinition = myContext.getResourceDefinition(targetResourceType);
        } catch (DataFormatException e) {
            throw new InvalidRequestException("Invalid resource type: " + targetResourceType);
        }

        RuntimeSearchParam owningParameterDef = targetResourceDefinition
                .getSearchParam(parameterName.replaceAll("\\..*", ""));
        if (owningParameterDef == null) {
            throw new InvalidRequestException(
                    "Unknown parameter name: " + targetResourceType + ':' + parameterName);
        }

        owningParameterDef = targetResourceDefinition.getSearchParam(owningParameter);
        if (owningParameterDef == null) {
            throw new InvalidRequestException(
                    "Unknown parameter name: " + targetResourceType + ':' + owningParameter);
        }

        Class<? extends IBaseResource> resourceType = targetResourceDefinition.getImplementingClass();
        Set<Long> match = myCallingDao.processMatchUrl(matchUrl, resourceType);
        if (match.isEmpty()) {
            doSetPids(new ArrayList<Long>());
            return;
        }

        CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
        CriteriaQuery<Long> cq = builder.createQuery(Long.class);
        Root<ResourceLink> from = cq.from(ResourceLink.class);
        cq.select(from.get("myTargetResourcePid").as(Long.class));

        List<Predicate> predicates = new ArrayList<Predicate>();
        predicates.add(builder.equal(from.get("mySourceResourceType"), targetResourceType));
        predicates.add(from.get("mySourceResourcePid").in(match));
        predicates.add(createResourceLinkPathPredicate(myContext, owningParameter, from, resourceType));
        predicates.add(builder.equal(from.get("myTargetResourceType"), myResourceName));
        createPredicateResourceId(builder, cq, predicates, from.get("myId").as(Long.class));
        createPredicateLastUpdatedForResourceLink(builder, from, predicates);

        cq.where(toArray(predicates));

        TypedQuery<Long> q = myEntityManager.createQuery(cq);
        doSetPids(q.getResultList());
        if (doHaveNoResults()) {
            return;
        }

        return;
    }
}

From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java

private void addPredicateParamMissingResourceLink(String joinName, String theParamName) {
    CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
    CriteriaQuery<Long> cq = builder.createQuery(Long.class);
    Root<ResourceTable> from = cq.from(ResourceTable.class);
    cq.select(from.get("myId").as(Long.class));

    Subquery<Long> subQ = cq.subquery(Long.class);
    Root<ResourceLink> subQfrom = subQ.from(ResourceLink.class);
    subQ.select(subQfrom.get("mySourceResourcePid").as(Long.class));

    // subQ.where(builder.equal(subQfrom.get("myParamName"), theParamName));
    Predicate path = createResourceLinkPathPredicate(theParamName, subQfrom);
    subQ.where(path);//w  w  w.j  ava2s.c  o m

    List<Predicate> predicates = new ArrayList<Predicate>();
    createPredicateResourceId(builder, cq, predicates, from.get("myId").as(Long.class));
    predicates.add(builder.not(builder.in(from.get("myId")).value(subQ)));
    predicates.add(builder.equal(from.get("myResourceType"), myResourceName));

    cq.where(builder.and(toArray(predicates)));

    TypedQuery<Long> q = myEntityManager.createQuery(cq);
    List<Long> resultList = q.getResultList();
    doSetPids(new HashSet<Long>(resultList));
}

From source file:ch.puzzle.itc.mobiliar.business.server.boundary.ServerView.java

public List<ServerTuple> getNodeServers(String hostFilter, String appServerFilter, String runtimeFilter,
        String nodeFilter, String contextFilter) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();

    CriteriaQuery<ServerTuple> q = cb.createQuery(ServerTuple.class);

    //get Node ResType
    Root<ResourceEntity> node = q.from(ResourceEntity.class);
    Join<ResourceEntity, ResourceTypeEntity> nodeType = node.join("resourceType", JoinType.LEFT);
    Join<ResourceEntity, ReleaseEntity> nodeRelease = node.join("release", JoinType.LEFT);

    //get Props on node
    Join<ResourceEntity, ResourceContextEntity> resCtx = node.join("contexts", JoinType.LEFT);
    Join<ResourceContextEntity, ContextEntity> nodeCtx = resCtx.join("context", JoinType.LEFT);
    Join<ContextEntity, ContextEntity> nodeDomain = nodeCtx.join("parent", JoinType.LEFT);
    Join<ResourceContextEntity, PropertyEntity> nodeProp = resCtx.join("properties", JoinType.LEFT);
    Join<PropertyEntity, PropertyDescriptorEntity> nodePropType = nodeProp.join("descriptor", JoinType.LEFT);

    //get AppServer
    Join<ResourceEntity, ConsumedResourceRelationEntity> nodeResRel = node.join("consumedSlaveRelations",
            JoinType.LEFT);/*from w  w  w . ja v a  2 s. c  o  m*/
    Join<ConsumedResourceRelationEntity, ResourceEntity> appServer = nodeResRel.join("masterResource",
            JoinType.LEFT);
    Join<ResourceEntity, ReleaseEntity> asRelease = appServer.join("release", JoinType.LEFT);
    Join<ResourceEntity, ResourceTypeEntity> asType = appServer.join("resourceType", JoinType.LEFT);

    //get Runtime of as
    Join<ResourceEntity, ConsumedResourceRelationEntity> asResRel = appServer.join("consumedMasterRelations",
            JoinType.LEFT);
    Join<ConsumedResourceRelationEntity, ResourceEntity> asRuntime = asResRel.join("slaveResource",
            JoinType.LEFT);
    Join<ResourceEntity, ResourceTypeEntity> runtimeType = asRuntime.join("resourceType", JoinType.LEFT);

    q.select(cb.construct(ServerTuple.class, nodeProp.get("value"), appServer.get("name"), appServer.get("id"),
            asRelease.get("name"), asRuntime.get("name"), node.get("name"), node.get("id"),
            nodeRelease.get("name"), nodeDomain.get("name"), nodeDomain.get("id"), nodeCtx.get("name"),
            nodeCtx.get("id"), cb.literal(1) // true
    ));

    Predicate p = cb.and(cb.equal(nodeType.get("name"), DefaultResourceTypeDefinition.NODE.name()),
            cb.or(cb.equal(asType.get("name"), DefaultResourceTypeDefinition.APPLICATIONSERVER.name()),
                    cb.isNull(asType.get("name")) //nodes without appServer
            ),
            cb.or(cb.equal(runtimeType.get("name"), ResourceTypeEntity.RUNTIME),
                    cb.isNull(runtimeType.get("name"))),
            cb.isNotNull(nodeProp.get("value")), cb.equal(nodePropType.get("propertyName"), "hostName")

    );

    p = addFilters(p, cb, hostFilter, appServerFilter, runtimeFilter, nodeFilter, contextFilter,
            nodeProp.<String>get("value"), appServer.<String>get("name"), asRuntime.<String>get("name"),
            node.<String>get("name"), nodeCtx.<String>get("name"));

    q.where(p);

    TypedQuery<ServerTuple> query = entityManager.createQuery(q);
    List<ServerTuple> servers = query.getResultList();

    return servers;
}

From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java

private void addPredicateParamMissing(String joinName, String theParamName,
        Class<? extends BaseResourceIndexedSearchParam> theParamTable) {
    CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
    CriteriaQuery<Long> cq = builder.createQuery(Long.class);
    Root<ResourceTable> from = cq.from(ResourceTable.class);
    cq.select(from.get("myId").as(Long.class));

    Subquery<Long> subQ = cq.subquery(Long.class);
    Root<? extends BaseResourceIndexedSearchParam> subQfrom = subQ.from(theParamTable);
    subQ.select(subQfrom.get("myResourcePid").as(Long.class));
    Predicate subQname = builder.equal(subQfrom.get("myParamName"), theParamName);
    Predicate subQtype = builder.equal(subQfrom.get("myResourceType"), myResourceName);
    subQ.where(builder.and(subQtype, subQname));

    List<Predicate> predicates = new ArrayList<Predicate>();
    predicates.add(builder.not(builder.in(from.get("myId")).value(subQ)));
    predicates.add(builder.equal(from.get("myResourceType"), myResourceName));
    predicates.add(builder.isNull(from.get("myDeleted")));
    createPredicateResourceId(builder, cq, predicates, from.get("myId").as(Long.class));

    cq.where(builder.and(toArray(predicates)));

    ourLog.info("Adding :missing qualifier for parameter '{}'", theParamName);

    TypedQuery<Long> q = myEntityManager.createQuery(cq);
    doSetPids(q.getResultList());//from   ww  w  .  ja v a 2 s.  com
}

From source file:com.hiperium.dao.common.generic.GenericDAO.java

/**
 * /*from   w w w.j  av  a  2s  . com*/
 * @param criteriaBuilder
 * @param criteriaQuery
 * @param root
 * @param entity
 */
private <E> void constructQuery(CriteriaBuilder criteriaBuilder, final CriteriaQuery<E> criteriaQuery,
        Root<E> root, E entity) {
    Map<String, Object> properties = this.getEntityProperties(entity);
    CriteriaFieldConditions criteria = new CriteriaFieldConditions(properties);
    List<Predicate> predicateList = new ArrayList<Predicate>();
    // Add equality conditions conditions
    Set<String> equalityKeys = criteria.equality.keySet();
    for (String key : equalityKeys) {
        predicateList.add(criteriaBuilder.equal(root.get(key), criteria.equality.get(key)));
    }
    // Add like conditions
    Set<String> likeKeys = criteria.like.keySet();
    for (String key : likeKeys) {
        predicateList.add(criteriaBuilder.like(root.<String>get(key), criteria.like.get(key).toString()));
    }
    // Add composite conditions, only with equality conditions
    Set<String> compositeKeys = criteria.composite.keySet();
    for (String key : compositeKeys) {
        Object value = criteria.composite.get(key);
        try {
            if (value.toString().startsWith("class java.util")) {
                continue;
            } else if (StringUtils.containsIgnoreCase(key, PK_OBJECT_NAME)) {
                Map<String, Object> propsComposites = this.getEntityProperties(value, key);
                CriteriaFieldConditions compositeCriteria = new CriteriaFieldConditions(propsComposites);
                if (!compositeCriteria.equality.isEmpty()) {
                    Set<String> equalityKeysPk = compositeCriteria.equality.keySet();
                    for (String keyPk : equalityKeysPk) {
                        String pkValueName = keyPk.replace(PK_OBJECT_NAME.concat("."), "");
                        predicateList.add(criteriaBuilder.equal(root.get(PK_OBJECT_NAME).get(pkValueName),
                                compositeCriteria.equality.get(keyPk)));
                    }
                }
                if (!compositeCriteria.like.isEmpty()) {
                    Set<String> likeKeysPK = compositeCriteria.like.keySet();
                    for (String keyPk : likeKeysPK) {
                        String pkValueName = keyPk.replace(PK_OBJECT_NAME.concat("."), "");
                        Expression<String> expression = root.<String>get(PK_OBJECT_NAME).get(pkValueName);
                        predicateList.add(
                                criteriaBuilder.like(expression, compositeCriteria.like.get(keyPk).toString()));
                    }
                }
            }
        } catch (RuntimeException e) {
            continue;
        }
    }
    // Adding where stuff is necessary
    if (predicateList.size() == 1) {
        criteriaQuery.where(predicateList.get(0));
    } else if (predicateList.size() > 1) {
        Predicate[] predicateCriteria = new Predicate[predicateList.size()];
        predicateCriteria = predicateList.toArray(predicateCriteria);
        criteriaQuery.where(criteriaBuilder.and(predicateCriteria));
    }
}

From source file:com.ims.service.ProductStockInfoService.java

public List<ProductStockInfo> findProdStockInfoListFrom(final ProdStockSearchCriteria stockSearchCriteria) {
    Specification<ProductStockInfo> speci = new Specification<ProductStockInfo>() {
        @Override//from  w ww .j  av a 2s. c  o  m
        public Predicate toPredicate(Root<ProductStockInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            List<Predicate> predicates = new ArrayList<Predicate>();
            predicates.add(cb.equal(root.get("stockType"), stockSearchCriteria.getStockType()));
            if (StringUtils.isNotEmpty(stockSearchCriteria.getProdCategoryCode())) {
                predicates.add(cb.equal(root.get("categoryCode"), stockSearchCriteria.getProdCategoryCode()));
            }
            if (StringUtils.isNotEmpty(stockSearchCriteria.getProdCode())) {
                predicates.add(cb.like(root.<String>get("productCode"),
                        "%" + stockSearchCriteria.getProdCode() + "%"));
            }
            String compareCode = stockSearchCriteria.getCompareCode();
            if (StringUtils.isNotEmpty(compareCode) && stockSearchCriteria.isIncludeComparedValue()) {
                Path<ProductAmount> productAmount = root.<ProductAmount>get("productAmount");
                if (CompareCode.isEqual(compareCode)) {
                    predicates.add(
                            cb.equal(productAmount.get("totalAmount"), stockSearchCriteria.getStockAmount()));
                } else if (CompareCode.isGreater(compareCode)) {
                    predicates.add(cb.greaterThan(productAmount.<Integer>get("totalAmount"),
                            stockSearchCriteria.getStockAmount()));
                } else if (CompareCode.isLess(compareCode)) {
                    predicates.add(cb.lessThan(productAmount.<Integer>get("totalAmount"),
                            stockSearchCriteria.getStockAmount()));
                } else if (CompareCode.isGreaterOrEqual(compareCode)) {
                    predicates.add(cb.greaterThanOrEqualTo(productAmount.<Integer>get("totalAmount"),
                            stockSearchCriteria.getStockAmount()));
                } else if (CompareCode.isLessOrEqual(compareCode)) {
                    predicates.add(cb.lessThanOrEqualTo(productAmount.<Integer>get("totalAmount"),
                            stockSearchCriteria.getStockAmount()));
                } else if (CompareCode.isEqualAlertAmount(compareCode)) {
                    predicates.add(cb.equal(productAmount.get("totalAmount"), root.get("alertStockAmount")));
                } else if (CompareCode.isGreaterThanAlertAmount(compareCode)) {
                    predicates.add(cb.greaterThan(productAmount.<String>get("totalAmount"),
                            root.<String>get("alertStockAmount")));
                } else if (CompareCode.isLessThanAlertAmount(compareCode)) {
                    predicates.add(cb.lessThan(productAmount.<String>get("totalAmount"),
                            root.<String>get("alertStockAmount")));
                }

                if (stockSearchCriteria.isTransformAction()
                        && ((CompareCode.isLess(compareCode) || CompareCode.isLessOrEqual(compareCode)))) {
                    predicates.add(cb.greaterThan(productAmount.<Integer>get("totalAmount"), 0));
                }
            }

            query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])))
                    .orderBy(cb.desc(root.get("categoryCode")), cb.asc(root.get("productCode")));
            return null;
        }
    };

    return productStockInfoRepository.findAll(speci);
}

From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java

private void addPredicateQuantity(String theParamName, List<? extends IQueryParameterType> theList) {
    if (Boolean.TRUE.equals(theList.get(0).getMissing())) {
        addPredicateParamMissing("myParamsQuantity", theParamName, ResourceIndexedSearchParamQuantity.class);
        return;//from  w w  w.j ava2  s  .c  om
    }

    CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
    CriteriaQuery<Long> cq = builder.createQuery(Long.class);
    Root<ResourceIndexedSearchParamQuantity> from = cq.from(ResourceIndexedSearchParamQuantity.class);
    cq.select(from.get("myResourcePid").as(Long.class));

    List<Predicate> codePredicates = new ArrayList<Predicate>();
    for (IQueryParameterType nextOr : theList) {
        if (addPredicateMissingFalseIfPresent(builder, theParamName, from, codePredicates, nextOr)) {
            continue;
        }

        Predicate singleCode = createPredicateQuantity(builder, from, nextOr);
        codePredicates.add(singleCode);
    }

    List<Predicate> predicates = new ArrayList<Predicate>();
    predicates.add(builder.equal(from.get("myResourceType"), myResourceName));
    predicates.add(builder.equal(from.get("myParamName"), theParamName));
    predicates.add(builder.or(toArray(codePredicates)));
    createPredicateResourceId(builder, cq, predicates, from.get("myResourcePid").as(Long.class));
    createPredicateLastUpdatedForIndexedSearchParam(builder, from, predicates);

    cq.where(builder.and(toArray(predicates)));

    TypedQuery<Long> q = myEntityManager.createQuery(cq);
    doSetPids(new HashSet<Long>(q.getResultList()));
}

From source file:org.finra.herd.dao.impl.BusinessObjectFormatDaoImpl.java

@Override
public List<BusinessObjectFormatKey> getBusinessObjectFormatsWithFilters(
        BusinessObjectDefinitionKey businessObjectDefinitionKey, String businessObjectFormatUsage,
        boolean latestBusinessObjectFormatVersion) {
    // Create the criteria builder and a tuple style criteria query.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteria = builder.createTupleQuery();

    // The criteria root is the business object format.
    Root<BusinessObjectFormatEntity> businessObjectFormatEntity = criteria
            .from(BusinessObjectFormatEntity.class);

    // Join to the other tables we can filter on.
    Join<BusinessObjectFormatEntity, BusinessObjectDefinitionEntity> businessObjectDefinitionEntity = businessObjectFormatEntity
            .join(BusinessObjectFormatEntity_.businessObjectDefinition);
    Join<BusinessObjectFormatEntity, FileTypeEntity> fileTypeEntity = businessObjectFormatEntity
            .join(BusinessObjectFormatEntity_.fileType);
    Join<BusinessObjectDefinitionEntity, NamespaceEntity> namespaceEntity = businessObjectDefinitionEntity
            .join(BusinessObjectDefinitionEntity_.namespace);

    // Get the columns.
    Path<String> namespaceCodeColumn = namespaceEntity.get(NamespaceEntity_.code);
    Path<String> businessObjectDefinitionNameColumn = businessObjectDefinitionEntity
            .get(BusinessObjectDefinitionEntity_.name);
    Path<String> businessObjectFormatUsageColumn = businessObjectFormatEntity
            .get(BusinessObjectFormatEntity_.usage);
    Path<String> fileTypeCodeColumn = fileTypeEntity.get(FileTypeEntity_.code);
    Path<Integer> businessObjectFormatVersionColumn = businessObjectFormatEntity
            .get(BusinessObjectFormatEntity_.businessObjectFormatVersion);
    Expression<Integer> maxBusinessObjectFormatVersionExpression = builder
            .max(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.businessObjectFormatVersion));

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate queryRestriction = builder.equal(builder.upper(namespaceEntity.get(NamespaceEntity_.code)),
            businessObjectDefinitionKey.getNamespace().toUpperCase());
    queryRestriction = builder.and(queryRestriction,
            builder.equal(/*www  .  j ava2 s  .c om*/
                    builder.upper(businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.name)),
                    businessObjectDefinitionKey.getBusinessObjectDefinitionName().toUpperCase()));

    // Add the business object format usage where parameter is not empty
    if (StringUtils.isNotEmpty(businessObjectFormatUsage)) {
        queryRestriction = builder.and(queryRestriction,
                builder.equal(builder.upper(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.usage)),
                        businessObjectFormatUsage.toUpperCase()));
    }

    // Add the select clause.
    criteria.multiselect(namespaceCodeColumn, businessObjectDefinitionNameColumn,
            businessObjectFormatUsageColumn, fileTypeCodeColumn,
            latestBusinessObjectFormatVersion ? maxBusinessObjectFormatVersionExpression
                    : businessObjectFormatVersionColumn);

    // Add the where clause.
    criteria.where(queryRestriction);

    // If only the latest (maximum) business object format versions to be returned, create and apply the group by clause.
    if (latestBusinessObjectFormatVersion) {
        List<Expression<?>> grouping = new ArrayList<>();
        grouping.add(namespaceCodeColumn);
        grouping.add(businessObjectDefinitionNameColumn);
        grouping.add(businessObjectFormatUsageColumn);
        grouping.add(fileTypeCodeColumn);
        criteria.groupBy(grouping);
    }

    // Add the order by clause.
    List<Order> orderBy = new ArrayList<>();
    orderBy.add(builder.asc(businessObjectFormatUsageColumn));
    orderBy.add(builder.asc(fileTypeCodeColumn));
    if (!latestBusinessObjectFormatVersion) {
        orderBy.add(builder.asc(businessObjectFormatVersionColumn));
    }
    criteria.orderBy(orderBy);

    // Run the query to get a list of tuples back.
    List<Tuple> tuples = entityManager.createQuery(criteria).getResultList();

    // Populate the "keys" objects from the returned tuples (i.e. 1 tuple for each row).
    List<BusinessObjectFormatKey> businessObjectFormatKeys = new ArrayList<>();
    for (Tuple tuple : tuples) {
        BusinessObjectFormatKey businessObjectFormatKey = new BusinessObjectFormatKey();
        businessObjectFormatKeys.add(businessObjectFormatKey);
        businessObjectFormatKey.setNamespace(tuple.get(namespaceCodeColumn));
        businessObjectFormatKey.setBusinessObjectDefinitionName(tuple.get(businessObjectDefinitionNameColumn));
        businessObjectFormatKey.setBusinessObjectFormatUsage(tuple.get(businessObjectFormatUsageColumn));
        businessObjectFormatKey.setBusinessObjectFormatFileType(tuple.get(fileTypeCodeColumn));
        businessObjectFormatKey.setBusinessObjectFormatVersion(
                tuple.get(latestBusinessObjectFormatVersion ? maxBusinessObjectFormatVersionExpression
                        : businessObjectFormatVersionColumn));
    }

    return businessObjectFormatKeys;
}

From source file:ch.puzzle.itc.mobiliar.business.server.boundary.ServerView.java

public List<ServerTuple> getAppServers(String hostFilter, String appServerFilter, String runtimeFilter,
        String nodeFilter, String contextFilter) {

    CriteriaBuilder cb = entityManager.getCriteriaBuilder();

    CriteriaQuery<ServerTuple> q = cb.createQuery(ServerTuple.class);

    //get Node ResType
    Root<ResourceEntity> node = q.from(ResourceEntity.class);
    Join<ResourceEntity, ResourceTypeEntity> nodeType = node.join("resourceType", JoinType.LEFT);
    Join<ResourceEntity, ReleaseEntity> nodeRelease = node.join("release", JoinType.LEFT);

    //get AppServer
    Join<ResourceEntity, ConsumedResourceRelationEntity> nodeResRel = node.join("consumedSlaveRelations",
            JoinType.LEFT);//from  ww  w . jav a2s.c  o  m
    Join<ConsumedResourceRelationEntity, ResourceEntity> appServer = nodeResRel.join("masterResource",
            JoinType.LEFT);
    Join<ResourceEntity, ReleaseEntity> asRelease = appServer.join("release", JoinType.LEFT);
    Join<ResourceEntity, ResourceTypeEntity> asType = appServer.join("resourceType", JoinType.LEFT);

    //get Runtime of as
    Join<ResourceEntity, ConsumedResourceRelationEntity> asResRel = appServer.join("consumedMasterRelations",
            JoinType.LEFT);
    Join<ConsumedResourceRelationEntity, ResourceEntity> asRuntime = asResRel.join("slaveResource",
            JoinType.LEFT);
    Join<ResourceEntity, ResourceTypeEntity> runtimeType = asRuntime.join("resourceType", JoinType.LEFT);

    //get Props between as and node
    Join<ConsumedResourceRelationEntity, ResourceRelationContextEntity> resRelCtx = nodeResRel.join("contexts",
            JoinType.LEFT);
    Join<ResourceRelationContextEntity, ContextEntity> asCtx = resRelCtx.join("context", JoinType.LEFT);
    Join<ContextEntity, ContextEntity> asDomain = asCtx.join("parent", JoinType.LEFT);

    Join<ResourceRelationContextEntity, PropertyEntity> asProp = resRelCtx.join("properties", JoinType.LEFT);
    //here an on clause should be added, so we don't get hostnames that are divined directly on the node multiple times (and descriptor.propertyName = 'hostName')
    //on support was added in jpa 2.1 which is part of JEE 7
    Join<PropertyEntity, PropertyDescriptorEntity> asPropType = asProp.join("descriptor", JoinType.LEFT);

    q.select(cb.construct(ServerTuple.class, asProp.get("value"), appServer.get("name"), appServer.get("id"),
            asRelease.get("name"), asRuntime.get("name"), node.get("name"), node.get("id"),
            nodeRelease.get("name"), asDomain.get("name"), asDomain.get("id"), asCtx.get("name"),
            asCtx.get("id"), cb.literal(0) //false
    ));

    Predicate p = cb.and(cb.equal(nodeType.get("name"), DefaultResourceTypeDefinition.NODE.name()),
            cb.equal(asType.get("name"), DefaultResourceTypeDefinition.APPLICATIONSERVER.name()),
            cb.or(cb.equal(runtimeType.get("name"), ResourceTypeEntity.RUNTIME),
                    cb.isNull(runtimeType.get("name"))),
            cb.isNotNull(asProp.get("value")), cb.equal(asPropType.get("propertyName"), "hostName"));

    p = addFilters(p, cb, hostFilter, appServerFilter, runtimeFilter, nodeFilter, contextFilter,
            asProp.<String>get("value"), appServer.<String>get("name"), asRuntime.<String>get("name"),
            node.<String>get("name"), asCtx.<String>get("name"));

    q.where(p);

    TypedQuery<ServerTuple> query = entityManager.createQuery(q);
    List<ServerTuple> servers = query.getResultList();

    return servers;
}

From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java

private void addPredicateString(String theParamName, List<? extends IQueryParameterType> theList) {
    if (Boolean.TRUE.equals(theList.get(0).getMissing())) {
        addPredicateParamMissing("myParamsString", theParamName, ResourceIndexedSearchParamString.class);
        return;// w w w.ja  v  a2  s .c  o m
    }

    CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
    CriteriaQuery<Long> cq = builder.createQuery(Long.class);
    Root<ResourceIndexedSearchParamString> from = cq.from(ResourceIndexedSearchParamString.class);
    cq.select(from.get("myResourcePid").as(Long.class));

    List<Predicate> codePredicates = new ArrayList<Predicate>();
    for (IQueryParameterType nextOr : theList) {
        IQueryParameterType theParameter = nextOr;
        if (addPredicateMissingFalseIfPresent(builder, theParamName, from, codePredicates, nextOr)) {
            continue;
        }

        Predicate singleCode = createPredicateString(theParameter, theParamName, builder, from);
        codePredicates.add(singleCode);
    }

    List<Predicate> predicates = new ArrayList<Predicate>();
    predicates.add(builder.equal(from.get("myResourceType"), myResourceName));
    predicates.add(builder.equal(from.get("myParamName"), theParamName));
    predicates.add(builder.or(toArray(codePredicates)));

    createPredicateResourceId(builder, cq, predicates, from.get("myResourcePid").as(Long.class));
    createPredicateLastUpdatedForIndexedSearchParam(builder, from, predicates);

    cq.where(builder.and(toArray(predicates)));

    TypedQuery<Long> q = myEntityManager.createQuery(cq);
    doSetPids(new HashSet<Long>(q.getResultList()));
}