Example usage for javax.persistence.criteria CriteriaBuilder and

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

Introduction

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

Prototype

Predicate and(Expression<Boolean> x, Expression<Boolean> y);

Source Link

Document

Create a conjunction of the given boolean expressions.

Usage

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

private Set<Long> addPredicateId(Set<Long> theExistingPids, Set<Long> thePids) {
    if (thePids == null || thePids.isEmpty()) {
        return Collections.emptySet();
    }//from w  ww  .ja  v  a  2  s. c  o  m

    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));

    Predicate typePredicate = builder.equal(from.get("myResourceType"), myResourceName);
    Predicate idPrecidate = from.get("myId").in(thePids);

    cq.where(builder.and(typePredicate, idPrecidate));

    TypedQuery<Long> q = myEntityManager.createQuery(cq);
    HashSet<Long> found = new HashSet<Long>(q.getResultList());
    if (!theExistingPids.isEmpty()) {
        theExistingPids.retainAll(found);
    }

    return found;
}

From source file:net.shopxx.dao.impl.StatisticDaoImpl.java

public List<Statistic> analyze(Statistic.Period period, Date beginDate, Date endDate) {
    Assert.notNull(period);/*w w w.  j  av a  2 s.c  o m*/

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Statistic> criteriaQuery = criteriaBuilder.createQuery(Statistic.class);
    Root<Statistic> root = criteriaQuery.from(Statistic.class);
    switch (period) {
    case year:
        criteriaQuery.select(criteriaBuilder.construct(Statistic.class, root.get("year"),
                criteriaBuilder.sum(root.<Long>get("registerMemberCount")),
                criteriaBuilder.sum(root.<Long>get("createOrderCount")),
                criteriaBuilder.sum(root.<Long>get("completeOrderCount")),
                criteriaBuilder.sum(root.<BigDecimal>get("createOrderAmount")),
                criteriaBuilder.sum(root.<BigDecimal>get("completeOrderAmount"))));
        criteriaQuery.groupBy(root.get("year"));
        break;
    case month:
        criteriaQuery.select(criteriaBuilder.construct(Statistic.class, root.get("year"), root.get("month"),
                criteriaBuilder.sum(root.<Long>get("registerMemberCount")),
                criteriaBuilder.sum(root.<Long>get("createOrderCount")),
                criteriaBuilder.sum(root.<Long>get("completeOrderCount")),
                criteriaBuilder.sum(root.<BigDecimal>get("createOrderAmount")),
                criteriaBuilder.sum(root.<BigDecimal>get("completeOrderAmount"))));
        criteriaQuery.groupBy(root.get("year"), root.get("month"));
        break;
    case day:
        criteriaQuery.select(criteriaBuilder.construct(Statistic.class, root.get("year"), root.get("month"),
                root.get("day"), root.<Long>get("registerMemberCount"), root.<Long>get("createOrderCount"),
                root.<Long>get("completeOrderCount"), root.<BigDecimal>get("createOrderAmount"),
                root.<BigDecimal>get("completeOrderAmount")));
        break;
    }
    Predicate restrictions = criteriaBuilder.conjunction();
    if (beginDate != null) {
        Calendar calendar = DateUtils.toCalendar(beginDate);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.or(criteriaBuilder.greaterThan(root.<Integer>get("year"), year),
                        criteriaBuilder.and(criteriaBuilder.equal(root.<Integer>get("year"), year),
                                criteriaBuilder.greaterThan(root.<Integer>get("month"), month)),
                        criteriaBuilder.and(criteriaBuilder.equal(root.<Integer>get("year"), year),
                                criteriaBuilder.equal(root.<Integer>get("month"), month),
                                criteriaBuilder.greaterThanOrEqualTo(root.<Integer>get("day"), day))));
    }
    if (endDate != null) {
        Calendar calendar = DateUtils.toCalendar(endDate);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.or(criteriaBuilder.lessThan(root.<Integer>get("year"), year),
                        criteriaBuilder.and(criteriaBuilder.equal(root.<Integer>get("year"), year),
                                criteriaBuilder.lessThan(root.<Integer>get("month"), month)),
                        criteriaBuilder.and(criteriaBuilder.equal(root.<Integer>get("year"), year),
                                criteriaBuilder.equal(root.<Integer>get("month"), month),
                                criteriaBuilder.lessThanOrEqualTo(root.<Integer>get("day"), day))));
    }
    criteriaQuery.where(restrictions);
    return entityManager.createQuery(criteriaQuery).getResultList();
}

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));
        }//www  .  ja  v a2 s.c  om
    } 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: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//from  www.ja v a2 s .  co 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:com.yunguchang.data.ApplicationRepository.java

public List<TBusApplyinfoEntity> getAllApplications(String coordinatorUserId, String reasonType, String status,
        DateTime startBefore, DateTime startAfter, DateTime endBefore, DateTime endAfter, Integer offset,
        Integer limit, OrderByParam orderByParam, PrincipalExt principalExt) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<TBusApplyinfoEntity> cq = cb.createQuery(TBusApplyinfoEntity.class);
    Root<TBusApplyinfoEntity> applyRoot = cq.from(TBusApplyinfoEntity.class);
    applyRoot.fetch(TBusApplyinfoEntity_.passenger);
    Fetch<TBusApplyinfoEntity, TSysUserEntity> fetchCoordinator = applyRoot
            .fetch(TBusApplyinfoEntity_.coordinator);
    applyRoot.fetch(TBusApplyinfoEntity_.department);
    Fetch<TBusApplyinfoEntity, TBusScheduleRelaEntity> scheduleFetch = applyRoot
            .fetch(TBusApplyinfoEntity_.schedule, JoinType.LEFT);
    scheduleFetch.fetch(TBusScheduleRelaEntity_.senduser, JoinType.LEFT);
    scheduleFetch.fetch(TBusScheduleRelaEntity_.reciveuser, JoinType.LEFT);
    Fetch<TBusScheduleRelaEntity, TBusScheduleCarEntity> fetchScheduleCar = scheduleFetch
            .fetch(TBusScheduleRelaEntity_.scheduleCars, JoinType.LEFT);
    fetchScheduleCar.fetch(TBusScheduleCarEntity_.car, JoinType.LEFT).fetch(TAzCarinfoEntity_.depot,
            JoinType.LEFT);/*from   w ww .jav a2s .  c o  m*/
    fetchScheduleCar.fetch(TBusScheduleCarEntity_.driver, JoinType.LEFT).fetch(TRsDriverinfoEntity_.department,
            JoinType.LEFT);
    Predicate predicate = cb.conjunction();
    if (coordinatorUserId != null) {
        Join<TBusApplyinfoEntity, TSysUserEntity> joinCoordinator = (Join<TBusApplyinfoEntity, TSysUserEntity>) fetchCoordinator;
        predicate = cb.and(predicate, cb.equal(joinCoordinator.get(TSysUserEntity_.userid), coordinatorUserId));
    }
    if (reasonType != null) {
        predicate = cb.and(predicate, cb.equal(applyRoot.get(TBusApplyinfoEntity_.reason), reasonType));
    }
    if (status != null) {
        if (status.indexOf(":") < 0) {
            predicate = cb.and(predicate, cb.equal(applyRoot.get(TBusApplyinfoEntity_.status), status));
        } else {
            String[] statusList = status.split(":");
            predicate = cb.and(predicate,
                    applyRoot.get(TBusApplyinfoEntity_.status).in(Arrays.asList(statusList)));
        }
    }

    if (startBefore != null) {
        predicate = cb.and(predicate,
                cb.lessThanOrEqualTo(applyRoot.get(TBusApplyinfoEntity_.begintime), startBefore));
    }

    if (startAfter != null) {
        predicate = cb.and(predicate,
                cb.greaterThanOrEqualTo(applyRoot.get(TBusApplyinfoEntity_.begintime), startAfter));
    }

    if (endBefore != null) {
        predicate = cb.and(predicate,
                cb.lessThanOrEqualTo(applyRoot.get(TBusApplyinfoEntity_.endtime), endBefore));
    }

    if (endAfter != null) {
        predicate = cb.and(predicate,
                cb.greaterThanOrEqualTo(applyRoot.get(TBusApplyinfoEntity_.endtime), endAfter));
    }

    cq.where(predicate);

    List<Order> orders = new ArrayList<>();
    if (orderByParam != null) {
        for (OrderByParam.OrderBy orderBy : orderByParam.getOrderBies()) {
            Order order = null;
            if (orderBy.getFiled().toLowerCase().equals("start".toLowerCase())) {
                order = cb.desc(applyRoot.get(TBusApplyinfoEntity_.begintime));
            }
            if (order != null && !orderBy.isAsc()) {
                order = order.reverse();
            }
            if (order != null) {
                orders.add(order);
            }
        }

    }
    if (orders.size() == 0) {
        cq.orderBy(cb.desc(applyRoot.get(TBusApplyinfoEntity_.begintime)));
    } else {
        cq.orderBy(orders);
    }

    TypedQuery<TBusApplyinfoEntity> query = em.createQuery(cq);

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

    applySecurityFilter("applications", principalExt);

    return query.getResultList();
}

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

private Subquery<TBusScheduleCarEntity> applyOverlapScheduleCarSubquery(
        Subquery<TBusScheduleCarEntity> overlapScheduleCarSubQuery, String[] applicationIds,
        Root<TAzCarinfoEntity> carRoot, Root<TRsDriverinfoEntity> driverRoot, CriteriaBuilder cb,
        PrincipalExt principalExt) {//from  ww  w. jav  a2s  . c o m
    Root<TBusScheduleCarEntity> subScheduleCarRoot = overlapScheduleCarSubQuery
            .from(TBusScheduleCarEntity.class);
    overlapScheduleCarSubQuery.select(subScheduleCarRoot);

    Path<DateTime> scheduleStartTime = subScheduleCarRoot.get(TBusScheduleCarEntity_.schedule)
            .get(TBusScheduleRelaEntity_.starttime);
    Path<DateTime> scheduleEndTime = subScheduleCarRoot.get(TBusScheduleCarEntity_.schedule)
            .get(TBusScheduleRelaEntity_.endtime);

    DateTime applicationStartTime = null;
    DateTime applicationEndTime = null;
    for (String applicationId : applicationIds) {
        TBusApplyinfoEntity applicationEntity = getApplicationById(applicationId, principalExt);
        if (applicationEntity == null) {
            throw logger.entityNotFound(TBusApplyinfoEntity.class, applicationId);
        }
        if (applicationStartTime == null || applicationEndTime.isAfter(applicationEntity.getBegintime())) {
            applicationStartTime = applicationEntity.getBegintime();
        }
        if (applicationEndTime == null || applicationEndTime.isBefore(applicationEntity.getEndtime())) {
            applicationEndTime = applicationEntity.getEndtime();
        }

    }

    if (applicationStartTime == null || applicationEndTime == null) {
        throw logger.invalidApplication(Arrays.deepToString(applicationIds));
    }

    Predicate predicate = cb.and(
            cb.or(cb.and(cb.between(scheduleStartTime, applicationStartTime, applicationEndTime)),
                    cb.and(cb.between(scheduleEndTime, applicationStartTime, applicationEndTime)),
                    cb.and(cb.lessThan(scheduleStartTime, applicationStartTime),
                            cb.greaterThan(scheduleEndTime, applicationEndTime))),
            subScheduleCarRoot.get(TBusScheduleCarEntity_.status).in(ScheduleStatus.AWAITING.id()));
    if (driverRoot != null) {
        predicate = cb.and(predicate,
                cb.and(cb.equal(subScheduleCarRoot.get(TBusScheduleCarEntity_.car), carRoot),
                        cb.equal(subScheduleCarRoot.get(TBusScheduleCarEntity_.driver), driverRoot)));
    } else {
        predicate = cb.and(predicate, cb.equal(subScheduleCarRoot.get(TBusScheduleCarEntity_.car), carRoot));
    }

    overlapScheduleCarSubQuery.where(predicate);
    return overlapScheduleCarSubQuery;
}

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());//  w ww . j a v a  2  s.c  o  m
}

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

private boolean addPredicateMissingFalseIfPresentForResourceLink(CriteriaBuilder theBuilder,
        String theParamName, Root<? extends ResourceLink> from, List<Predicate> codePredicates,
        IQueryParameterType nextOr) {// w ww .j  ava 2s.  c om
    boolean missingFalse = false;
    if (nextOr.getMissing() != null) {
        if (nextOr.getMissing().booleanValue() == true) {
            throw new InvalidRequestException(myContext.getLocalizer().getMessage(BaseHapiFhirResourceDao.class,
                    "multipleParamsWithSameNameOneIsMissingTrue", theParamName));
        }
        Predicate singleCode = from.get("mySourceResource").isNotNull();
        Predicate name = createResourceLinkPathPredicate(theParamName, from);
        codePredicates.add(theBuilder.and(name, singleCode));
        missingFalse = true;
    }
    return missingFalse;
}

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

private boolean addPredicateMissingFalseIfPresent(CriteriaBuilder theBuilder, String theParamName,
        Root<? extends BaseResourceIndexedSearchParam> from, List<Predicate> codePredicates,
        IQueryParameterType nextOr) {/*w  ww  .j  a  v a2 s  . co m*/
    boolean missingFalse = false;
    if (nextOr.getMissing() != null) {
        if (nextOr.getMissing().booleanValue() == true) {
            throw new InvalidRequestException(myContext.getLocalizer().getMessage(BaseHapiFhirResourceDao.class,
                    "multipleParamsWithSameNameOneIsMissingTrue", theParamName));
        }
        Predicate singleCode = from.get("myId").isNotNull();
        Predicate name = theBuilder.equal(from.get("myParamName"), theParamName);
        codePredicates.add(theBuilder.and(name, singleCode));
        missingFalse = true;
    }
    return missingFalse;
}

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

private Set<Long> addPredicateLanguage(Set<Long> thePids, List<List<? extends IQueryParameterType>> theList) {
    if (theList == null || theList.isEmpty()) {
        return thePids;
    }/*from ww w  .ja v  a2 s.co  m*/
    if (theList.size() > 1) {
        throw new InvalidRequestException(
                "Language parameter can not have more than one AND value, found " + theList.size());
    }

    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));

    Set<String> values = new HashSet<String>();
    for (IQueryParameterType next : theList.get(0)) {
        if (next instanceof StringParam) {
            String nextValue = ((StringParam) next).getValue();
            if (isBlank(nextValue)) {
                continue;
            }
            values.add(nextValue);
        } else {
            throw new InternalErrorException("Lanugage parameter must be of type "
                    + StringParam.class.getCanonicalName() + " - Got " + next.getClass().getCanonicalName());
        }
    }

    if (values.isEmpty()) {
        return thePids;
    }

    Predicate typePredicate = builder.equal(from.get("myResourceType"), myResourceName);
    Predicate langPredicate = from.get("myLanguage").as(String.class).in(values);
    Predicate masterCodePredicate = builder.and(typePredicate, langPredicate);

    if (thePids.size() > 0) {
        Predicate inPids = (from.get("myId").in(thePids));
        cq.where(builder.and(masterCodePredicate, inPids));
    } else {
        cq.where(masterCodePredicate);
    }

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