Example usage for javax.persistence.criteria CriteriaBuilder isNull

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

Introduction

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

Prototype

Predicate isNull(Expression<?> x);

Source Link

Document

Create a predicate to test whether the expression is null.

Usage

From source file:com.yunguchang.data.ApplicationRepository.java

public List<TAzCarinfoEntity> listAllCandidateCars(String[] applicationIds, String keyword, Integer offset,
        Integer limit, PrincipalExt principalExt) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<TAzCarinfoEntity> cq = cb.createQuery(TAzCarinfoEntity.class);
    Root<TAzCarinfoEntity> carRoot = cq.from(TAzCarinfoEntity.class);
    carRoot.fetch(TAzCarinfoEntity_.driver, JoinType.LEFT);

    cq.select(carRoot);//from   w  w w. j  av  a2s. co m
    Subquery<TBusScheduleCarEntity> overlapScheduleCarSubQuery = cq.subquery(TBusScheduleCarEntity.class);

    applyOverlapScheduleCarSubquery(overlapScheduleCarSubQuery, applicationIds, carRoot, null, cb,
            principalExt);
    Predicate predicate = cb.and(cb.equal(carRoot.get(TAzCarinfoEntity_.clzt), "02"),
            cb.or(cb.equal(carRoot.get(TAzCarinfoEntity_.repairingState), RepairingState.NONE.id()),
                    cb.isNull(carRoot.get(TAzCarinfoEntity_.repairingState))

            ), cb.not(cb.exists(overlapScheduleCarSubQuery))

    );

    if (keyword != null) {
        predicate = cb.and(predicate,
                cb.or(cb.like(carRoot.get(TAzCarinfoEntity_.sysOrg).get(TSysOrgEntity_.orgname),
                        "%" + keyword + "%"),
                        cb.like(carRoot.get(TAzCarinfoEntity_.cphm), "%" + keyword + "%")));
    }

    cq.where(predicate);
    cq.orderBy(cb.asc(carRoot.get(TAzCarinfoEntity_.cphm)));
    TypedQuery<TAzCarinfoEntity> query = em.createQuery(cq);
    if (offset != null) {
        query.setFirstResult(offset);
    }

    if (limit != null) {
        query.setMaxResults(limit);
    }

    applySecurityFilter("cars", principalExt);

    return query.getResultList();
}

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

public Long count(Member favoriteMember, Boolean isMarketable, Boolean isList, Boolean isTop, Boolean isGift,
        Boolean isOutOfStock, Boolean isStockAlert) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Product> criteriaQuery = criteriaBuilder.createQuery(Product.class);
    Root<Product> root = criteriaQuery.from(Product.class);
    criteriaQuery.select(root);/*from   w  ww  .  j  a va  2s.  c om*/
    Predicate restrictions = criteriaBuilder.conjunction();
    if (favoriteMember != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.join("favoriteMembers"), favoriteMember));
    }
    if (isMarketable != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isMarketable"), isMarketable));
    }
    if (isList != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isList"), isList));
    }
    if (isTop != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isTop"), isTop));
    }
    if (isGift != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isGift"), isGift));
    }
    Path<Integer> stock = root.get("stock");
    Path<Integer> allocatedStock = root.get("allocatedStock");
    if (isOutOfStock != null) {
        if (isOutOfStock) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock),
                    criteriaBuilder.lessThanOrEqualTo(stock, allocatedStock));
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.isNull(stock),
                    criteriaBuilder.greaterThan(stock, allocatedStock)));
        }
    }
    if (isStockAlert != null) {
        Setting setting = SettingUtils.get();
        if (isStockAlert) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock),
                    criteriaBuilder.lessThanOrEqualTo(stock,
                            criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount())));
        } else {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.or(criteriaBuilder.isNull(stock), criteriaBuilder.greaterThan(stock,
                            criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount()))));
        }
    }
    criteriaQuery.where(restrictions);
    return super.count(criteriaQuery, null);
}

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

protected TagDefinition getTag(TagTypeEnum theTagType, String theScheme, String theTerm, String theLabel) {
    CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
    CriteriaQuery<TagDefinition> cq = builder.createQuery(TagDefinition.class);
    Root<TagDefinition> from = cq.from(TagDefinition.class);

    //@formatter:off
    if (isNotBlank(theScheme)) {
        cq.where(builder.and(builder.equal(from.get("myTagType"), theTagType),
                builder.equal(from.get("mySystem"), theScheme), builder.equal(from.get("myCode"), theTerm)));
    } else {/*from w  w  w  .  j  a v a 2s.c o m*/
        cq.where(builder.and(builder.equal(from.get("myTagType"), theTagType),
                builder.isNull(from.get("mySystem")), builder.equal(from.get("myCode"), theTerm)));
    }
    //@formatter:on

    TypedQuery<TagDefinition> q = myEntityManager.createQuery(cq);
    try {
        return q.getSingleResult();
    } catch (NoResultException e) {
        TagDefinition retVal = new TagDefinition(theTagType, theScheme, theTerm, theLabel);
        myEntityManager.persist(retVal);
        return retVal;
    }
}

From source file:gov.gtas.repository.CaseDispositionRepositoryImpl.java

@Override
public Pair<Long, List<Case>> findByCriteria(CaseRequestDto dto) {

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Case> q = cb.createQuery(Case.class);
    Root<Case> root = q.from(Case.class);
    List<Predicate> predicates = new ArrayList<>();

    TypedQuery<Case> typedQuery = em.createQuery(q);

    // sorting//www.  j  av  a  2 s  .c  o m
    if (dto.getSort() != null) {
        List<Order> orders = new ArrayList<>();
        for (SortOptionsDto sort : dto.getSort()) {
            Expression<?> e = root.get(sort.getColumn());
            Order order;
            if ("desc".equalsIgnoreCase(sort.getDir())) {
                order = cb.desc(e);
            } else {
                order = cb.asc(e);
            }
            orders.add(order);
        }
        q.orderBy(orders);
    }

    if (dto.getFlightId() != null) {
        predicates.add(cb.equal(root.<Long>get("flightId"), dto.getFlightId()));
    }

    if (dto.getPaxId() != null) {
        predicates.add(cb.equal(root.<Long>get("paxId"), dto.getPaxId()));
    }

    if (dto.getPaxName() != null) {
        String likeString = String.format("%%%s%%", dto.getPaxName().toUpperCase());
        predicates.add(cb.like(root.<String>get("paxName"), likeString));
    }

    if (dto.getLastName() != null) { // map this to full pax name
        String likeString = String.format("%%%s%%", dto.getLastName().toUpperCase());
        predicates.add(cb.like(root.<String>get("paxName"), likeString));
    }

    if (dto.getStatus() != null) {
        String likeString = String.format("%%%s%%", dto.getStatus().toUpperCase());
        predicates.add(cb.like(root.<String>get("status"), likeString));
    }

    if (dto.getFlightNumber() != null) {
        predicates.add(cb.equal(root.<Long>get("flightNumber"), dto.getFlightNumber()));
    }

    if (dto.getRuleCatId() != null) {
        predicates.add(cb.equal(root.<Long>get("highPriorityRuleCatId"), dto.getRuleCatId()));
    }

    Predicate etaCondition;
    if (dto.getEtaStart() != null && dto.getEtaEnd() != null) {

        Path<Date> eta = root.<Date>get("flightETADate");
        Predicate startPredicate = cb.or(cb.isNull(eta), cb.greaterThanOrEqualTo(eta, dto.getEtaStart()));
        Predicate endPredicate = cb.or(cb.isNull(eta), cb.lessThanOrEqualTo(eta, dto.getEtaEnd()));
        etaCondition = cb.and(startPredicate, endPredicate);
        predicates.add(etaCondition);
    }

    q.select(root).where(predicates.toArray(new Predicate[] {}));
    typedQuery = em.createQuery(q);

    // total count
    CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
    countQuery.select(cb.count(countQuery.from(Case.class))).where(predicates.toArray(new Predicate[] {}));
    Long count = em.createQuery(countQuery).getSingleResult();

    // pagination
    int pageNumber = dto.getPageNumber();
    int pageSize = dto.getPageSize();
    int firstResultIndex = (pageNumber - 1) * pageSize;
    typedQuery.setFirstResult(firstResultIndex);
    typedQuery.setMaxResults(dto.getPageSize());

    logger.debug(typedQuery.unwrap(org.hibernate.Query.class).getQueryString());
    List<Case> results = typedQuery.getResultList();

    return new ImmutablePair<>(count, results);

}

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

@Override
public IBundleProvider search(final SearchParameterMap theParams) {
    StopWatch w = new StopWatch();
    final InstantDt now = InstantDt.withCurrentTime();

    Set<Long> loadPids;
    if (theParams.isEmpty()) {
        loadPids = new HashSet<Long>();
        CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
        CriteriaQuery<Tuple> cq = builder.createTupleQuery();
        Root<ResourceTable> from = cq.from(ResourceTable.class);
        cq.multiselect(from.get("myId").as(Long.class));
        Predicate typeEquals = builder.equal(from.get("myResourceType"), myResourceName);
        Predicate notDeleted = builder.isNull(from.get("myDeleted"));
        cq.where(builder.and(typeEquals, notDeleted));

        TypedQuery<Tuple> query = myEntityManager.createQuery(cq);
        for (Tuple next : query.getResultList()) {
            loadPids.add(next.get(0, Long.class));
        }//  w w w  .  j a v a  2  s. co  m
    } else {
        loadPids = searchForIdsWithAndOr(theParams);
        if (loadPids.isEmpty()) {
            return new SimpleBundleProvider();
        }
    }

    final List<Long> pids;

    // Handle sorting if any was provided
    if (theParams.getSort() != null && isNotBlank(theParams.getSort().getParamName())) {
        List<Order> orders = new ArrayList<Order>();
        List<Predicate> predicates = new ArrayList<Predicate>();
        CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
        CriteriaQuery<Tuple> cq = builder.createTupleQuery();
        Root<ResourceTable> from = cq.from(ResourceTable.class);
        predicates.add(from.get("myId").in(loadPids));
        createSort(builder, from, theParams.getSort(), orders, predicates);
        if (orders.size() > 0) {
            Set<Long> originalPids = loadPids;
            loadPids = new LinkedHashSet<Long>();
            cq.multiselect(from.get("myId").as(Long.class));
            cq.where(predicates.toArray(new Predicate[0]));
            cq.orderBy(orders);

            TypedQuery<Tuple> query = myEntityManager.createQuery(cq);

            for (Tuple next : query.getResultList()) {
                loadPids.add(next.get(0, Long.class));
            }

            ourLog.info("Sort PID order is now: {}", loadPids);

            pids = new ArrayList<Long>(loadPids);

            // Any ressources which weren't matched by the sort get added to the bottom
            for (Long next : originalPids) {
                if (loadPids.contains(next) == false) {
                    pids.add(next);
                }
            }

        } else {
            pids = new ArrayList<Long>(loadPids);
        }
    } else {
        pids = new ArrayList<Long>(loadPids);
    }

    // Load _revinclude resources
    if (theParams.getRevIncludes() != null && theParams.getRevIncludes().isEmpty() == false) {
        loadReverseIncludes(pids, theParams.getRevIncludes());
    }

    IBundleProvider retVal = new IBundleProvider() {
        @Override
        public InstantDt getPublished() {
            return now;
        }

        @Override
        public List<IResource> getResources(final int theFromIndex, final int theToIndex) {
            TransactionTemplate template = new TransactionTemplate(myPlatformTransactionManager);
            return template.execute(new TransactionCallback<List<IResource>>() {
                @Override
                public List<IResource> doInTransaction(TransactionStatus theStatus) {
                    List<Long> pidsSubList = pids.subList(theFromIndex, theToIndex);

                    // Execute the query and make sure we return distinct results
                    List<IResource> retVal = new ArrayList<IResource>();
                    loadResourcesByPid(pidsSubList, retVal, BundleEntrySearchModeEnum.MATCH);

                    /*
                     * Load _include resources - Note that _revincludes are handled differently
                     * than _include ones, as they are counted towards the total count and paged,
                     * so they are loaded outside the bundle provider
                     */
                    if (theParams.getIncludes() != null && theParams.getIncludes().isEmpty() == false) {
                        Set<IdDt> previouslyLoadedPids = new HashSet<IdDt>();
                        for (IResource next : retVal) {
                            previouslyLoadedPids.add(next.getId().toUnqualifiedVersionless());
                        }

                        Set<IdDt> includePids = new HashSet<IdDt>();
                        List<IResource> resources = retVal;
                        do {
                            includePids.clear();

                            FhirTerser t = getContext().newTerser();
                            for (Include next : theParams.getIncludes()) {
                                for (IResource nextResource : resources) {
                                    RuntimeResourceDefinition def = getContext()
                                            .getResourceDefinition(nextResource);
                                    List<Object> values = getIncludeValues(t, next, nextResource, def);

                                    for (Object object : values) {
                                        if (object == null) {
                                            continue;
                                        }
                                        if (!(object instanceof BaseResourceReferenceDt)) {
                                            throw new InvalidRequestException("Path '" + next.getValue()
                                                    + "' produced non ResourceReferenceDt value: "
                                                    + object.getClass());
                                        }
                                        BaseResourceReferenceDt rr = (BaseResourceReferenceDt) object;
                                        if (rr.getReference().isEmpty()) {
                                            continue;
                                        }
                                        if (rr.getReference().isLocal()) {
                                            continue;
                                        }

                                        IdDt nextId = rr.getReference().toUnqualified();
                                        if (!previouslyLoadedPids.contains(nextId)) {
                                            includePids.add(nextId);
                                            previouslyLoadedPids.add(nextId);
                                        }
                                    }
                                }
                            }

                            resources = addResourcesAsIncludesById(retVal, includePids, resources);
                        } while (includePids.size() > 0
                                && previouslyLoadedPids.size() < getConfig().getIncludeLimit());

                        if (previouslyLoadedPids.size() >= getConfig().getIncludeLimit()) {
                            OperationOutcome oo = new OperationOutcome();
                            oo.addIssue().setSeverity(IssueSeverityEnum.WARNING).setDetails(
                                    "Not all _include resources were actually included as the request surpassed the limit of "
                                            + getConfig().getIncludeLimit() + " resources");
                            retVal.add(0, oo);
                        }
                    }

                    return retVal;
                }

            });
        }

        @Override
        public Integer preferredPageSize() {
            return theParams.getCount();
        }

        @Override
        public int size() {
            return pids.size();
        }
    };

    ourLog.info("Processed search for {} on {} in {}ms",
            new Object[] { myResourceName, theParams, w.getMillisAndRestart() });

    return retVal;
}

From source file:com.yunguchang.data.ApplicationRepository.java

public List<TRsDriverinfoEntity> listAllCandidateDrivers(String[] applicationIds, String carId, String keyword,
        Integer offset, Integer limit, PrincipalExt principalExt) {

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<TRsDriverinfoEntity> cq = cb.createQuery(TRsDriverinfoEntity.class);
    Root<TRsDriverinfoEntity> driverRoot = cq.from(TRsDriverinfoEntity.class);
    Root<TAzCarinfoEntity> carRoot = cq.from(TAzCarinfoEntity.class);
    cq.select(driverRoot);/*from  ww  w .  ja  va  2  s .  c  o m*/

    Subquery<TBusScheduleCarEntity> overlapScheduleCarSubQuery = cq.subquery(TBusScheduleCarEntity.class);

    applyOverlapScheduleCarSubquery(overlapScheduleCarSubQuery, applicationIds, carRoot, driverRoot, cb,
            principalExt);

    Subquery<TRsDriverinfoEntity> subqueryLicense = cq.subquery(TRsDriverinfoEntity.class);
    Root<TAzJzRelaEntity> licenseMapping = subqueryLicense.from(TAzJzRelaEntity.class);
    subqueryLicense.select(driverRoot);
    subqueryLicense.where(

            cb.equal(carRoot.get(TAzCarinfoEntity_.xszcx), licenseMapping.get(TAzJzRelaEntity_.xszcx)),
            cb.equal(licenseMapping.get(TAzJzRelaEntity_.jzyq),
                    driverRoot.get(TRsDriverinfoEntity_.drivecartype)));

    Predicate predicate = cb.and(cb.equal(carRoot.get(TAzCarinfoEntity_.id), carId),
            cb.equal(driverRoot.get(TRsDriverinfoEntity_.department), carRoot.get(TAzCarinfoEntity_.sysOrg)),
            cb.equal(driverRoot.get(TRsDriverinfoEntity_.enabled), "1"),
            cb.or(cb.exists(subqueryLicense), cb.isNull(driverRoot.get(TRsDriverinfoEntity_.drivecartype))

            ),

            cb.not(cb.exists(overlapScheduleCarSubQuery))

    );

    if (keyword != null) {
        predicate = cb.and(predicate,
                cb.or(cb.like(driverRoot.get(TRsDriverinfoEntity_.drivername), "%" + keyword + "%")));
    }

    cq.where(predicate);
    cq.orderBy(cb
            .asc(cb.function("casttogbk", String.class, cb.trim(driverRoot.get(TRsDriverinfoEntity_.drivername))

    )));
    TypedQuery<TRsDriverinfoEntity> query = em.createQuery(cq);
    if (offset != null) {
        query.setFirstResult(offset);
    }

    if (limit != null) {
        query.setMaxResults(limit);
    }

    return query.getResultList();

}

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

private TypedQuery<Long> createSearchAllByTypeQuery(DateRangeParam theLastUpdated) {
    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));
    List<Predicate> predicates = new ArrayList<Predicate>();
    predicates.add(builder.equal(from.get("myResourceType"), myResourceName));
    predicates.add(builder.isNull(from.get("myDeleted")));

    if (theLastUpdated != null) {
        predicates.addAll(createLastUpdatedPredicates(theLastUpdated, builder, from));
    }/*w w  w .ja va  2s  . c  o m*/

    cq.where(toArray(predicates));

    TypedQuery<Long> query = myEntityManager.createQuery(cq);
    return query;
}

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  .java 2s .  com
    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

public IBundleProvider search(final SearchParameterMap theParams) {
    myParams = theParams;//from  w w w  .j  av a  2  s  .  c  om
    StopWatch w = new StopWatch();

    doInitializeSearch();

    DateRangeParam lu = theParams.getLastUpdated();

    // Collection<Long> loadPids;
    if (theParams.getEverythingMode() != null) {

        Long pid = null;
        if (theParams.get(BaseResource.SP_RES_ID) != null) {
            StringParam idParm = (StringParam) theParams.get(BaseResource.SP_RES_ID).get(0).get(0);
            pid = BaseHapiFhirDao.translateForcedIdToPid(myResourceName, idParm.getValue(), myForcedIdDao);
        }

        if (theParams.containsKey(Constants.PARAM_CONTENT) || theParams.containsKey(Constants.PARAM_TEXT)) {
            List<Long> pids = mySearchDao.everything(myResourceName, theParams);
            if (pids.isEmpty()) {
                return doReturnProvider();
            }

            doSetPids(pids);

        } else {
            CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
            CriteriaQuery<Tuple> cq = builder.createTupleQuery();
            Root<ResourceTable> from = cq.from(ResourceTable.class);
            List<Predicate> predicates = new ArrayList<Predicate>();
            if (pid != null) {
                predicates.add(builder.equal(from.get("myId"), pid));
            }
            predicates.add(builder.equal(from.get("myResourceType"), myResourceName));
            predicates.add(builder.isNull(from.get("myDeleted")));
            cq.where(builder.and(SearchBuilder.toArray(predicates)));

            Join<Object, Object> join = from.join("myIncomingResourceLinks", JoinType.LEFT);
            cq.multiselect(from.get("myId").as(Long.class), join.get("mySourceResourcePid").as(Long.class));

            TypedQuery<Tuple> query = myEntityManager.createQuery(cq);
            Set<Long> pids = new HashSet<Long>();
            for (Tuple next : query.getResultList()) {
                pids.add(next.get(0, Long.class));
                Long nextLong = next.get(1, Long.class);
                if (nextLong != null) {
                    pids.add(nextLong);
                }
            }
            doSetPids(pids);

        }

    } else if (theParams.isEmpty()) {

        TypedQuery<Long> query = createSearchAllByTypeQuery(lu);
        doSetPids(query.getResultList());

    } else {

        if (mySearchDao == null) {
            if (theParams.containsKey(Constants.PARAM_TEXT)) {
                throw new InvalidRequestException(
                        "Fulltext search is not enabled on this service, can not process parameter: "
                                + Constants.PARAM_TEXT);
            } else if (theParams.containsKey(Constants.PARAM_CONTENT)) {
                throw new InvalidRequestException(
                        "Fulltext search is not enabled on this service, can not process parameter: "
                                + Constants.PARAM_CONTENT);
            }
        } else {
            List<Long> searchResultPids = mySearchDao.search(myResourceName, theParams);
            if (searchResultPids != null) {
                if (searchResultPids.isEmpty()) {
                    return doReturnProvider();
                }
                doSetPids(searchResultPids);
            }
        }

        if (!theParams.isEmpty()) {
            searchForIdsWithAndOr(theParams, lu);
        }

    }

    // // Load _include and _revinclude before filter and sort in everything mode
    // if (theParams.getEverythingMode() != null) {
    // if (theParams.getRevIncludes() != null && theParams.getRevIncludes().isEmpty() == false) {
    // loadPids.addAll(loadReverseIncludes(loadPids, theParams.getRevIncludes(), true,
    // theParams.getEverythingMode()));
    // loadPids.addAll(loadReverseIncludes(loadPids, theParams.getIncludes(), false, theParams.getEverythingMode()));
    // }
    // }

    if (doHaveNoResults()) {
        return doReturnProvider();
    }

    // Handle _lastUpdated
    if (lu != null) {
        filterResourceIdsByLastUpdated(lu);

        if (doHaveNoResults()) {
            return doReturnProvider();
        }
    }

    // Handle sorting if any was provided
    processSort(theParams);

    ourLog.info(" {} on {} in {}ms", new Object[] { myResourceName, theParams, w.getMillisAndRestart() });
    return doReturnProvider();
}

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);//  w  w  w  .j  av a 2 s .co 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;
}