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:org.finra.herd.dao.impl.BusinessObjectFormatDaoImpl.java

@Override
public List<BusinessObjectFormatEntity> getLatestVersionBusinessObjectFormatsByBusinessObjectDefinition(
        BusinessObjectDefinitionKey businessObjectDefinitionKey) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<BusinessObjectFormatEntity> criteria = builder.createQuery(BusinessObjectFormatEntity.class);

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

    // 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(//from   w  w  w.  ja va2s .  com
                    builder.upper(businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.name)),
                    businessObjectDefinitionKey.getBusinessObjectDefinitionName().toUpperCase()));

    // Add the order by clause.
    List<Order> orderBy = new ArrayList<>();
    orderBy.add(builder.asc(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.usage)));
    orderBy.add(builder.asc(fileTypeEntity.get(FileTypeEntity_.code)));

    queryRestriction = builder.and(queryRestriction,
            builder.equal(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.latestVersion), true));

    criteria.orderBy(orderBy);
    // Add the where clause.
    criteria.where(queryRestriction);
    return entityManager.createQuery(criteria).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));
        }/* w  w w  .  jav  a 2 s  .  c o  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:io.apiman.manager.api.jpa.JpaStorage.java

/**
 * @see io.apiman.manager.api.core.IStorageQuery#getUserMemberships(java.lang.String)
 *//*from   w  ww .  j a va  2s . c o m*/
@Override
public Set<RoleMembershipBean> getUserMemberships(String userId) throws StorageException {
    Set<RoleMembershipBean> memberships = new HashSet<>();
    beginTx();
    try {
        EntityManager entityManager = getActiveEntityManager();
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<RoleMembershipBean> criteriaQuery = builder.createQuery(RoleMembershipBean.class);
        Root<RoleMembershipBean> from = criteriaQuery.from(RoleMembershipBean.class);
        criteriaQuery.where(builder.equal(from.get("userId"), userId));
        TypedQuery<RoleMembershipBean> typedQuery = entityManager.createQuery(criteriaQuery);
        List<RoleMembershipBean> resultList = typedQuery.getResultList();
        memberships.addAll(resultList);
        return memberships;
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
        throw new StorageException(t);
    } finally {
        rollbackTx();
    }
}

From source file:io.apiman.manager.api.jpa.JpaStorage.java

/**
 * @see io.apiman.manager.api.core.IStorageQuery#getOrgMemberships(java.lang.String)
 */// w w  w  .j av  a2 s  .com
@Override
public Set<RoleMembershipBean> getOrgMemberships(String organizationId) throws StorageException {
    Set<RoleMembershipBean> memberships = new HashSet<>();
    beginTx();
    try {
        EntityManager entityManager = getActiveEntityManager();
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<RoleMembershipBean> criteriaQuery = builder.createQuery(RoleMembershipBean.class);
        Root<RoleMembershipBean> from = criteriaQuery.from(RoleMembershipBean.class);
        criteriaQuery.where(builder.equal(from.get("organizationId"), organizationId));
        TypedQuery<RoleMembershipBean> typedQuery = entityManager.createQuery(criteriaQuery);
        List<RoleMembershipBean> resultList = typedQuery.getResultList();
        memberships.addAll(resultList);
        return memberships;
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
        throw new StorageException(t);
    } finally {
        rollbackTx();
    }
}

From source file:io.apiman.manager.api.jpa.JpaStorage.java

/**
 * @see io.apiman.manager.api.core.IStorageQuery#getPermissions(java.lang.String)
 *//*from  w ww  . j  av a 2 s  .c o  m*/
@Override
public Set<PermissionBean> getPermissions(String userId) throws StorageException {
    Set<PermissionBean> permissions = new HashSet<>();
    beginTx();
    try {
        EntityManager entityManager = getActiveEntityManager();
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<RoleMembershipBean> criteriaQuery = builder.createQuery(RoleMembershipBean.class);
        Root<RoleMembershipBean> from = criteriaQuery.from(RoleMembershipBean.class);
        criteriaQuery.where(builder.equal(from.get("userId"), userId));
        TypedQuery<RoleMembershipBean> typedQuery = entityManager.createQuery(criteriaQuery);
        typedQuery.setMaxResults(500);
        List<RoleMembershipBean> resultList = typedQuery.getResultList();
        for (RoleMembershipBean membership : resultList) {
            RoleBean role = getRoleInternal(membership.getRoleId());
            String qualifier = membership.getOrganizationId();
            for (PermissionType permission : role.getPermissions()) {
                PermissionBean p = new PermissionBean();
                p.setName(permission);
                p.setOrganizationId(qualifier);
                permissions.add(p);
            }
        }
        return permissions;
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
        throw new StorageException(t);
    } finally {
        rollbackTx();
    }
}

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

private void filterResourceIdsByLastUpdated(final 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> lastUpdatedPredicates = createLastUpdatedPredicates(theLastUpdated, builder, from);
    createPredicateResourceId(builder, cq, lastUpdatedPredicates, from.get("myId").as(Long.class));

    cq.where(SearchBuilder.toArray(lastUpdatedPredicates));
    TypedQuery<Long> query = myEntityManager.createQuery(cq);

    List<Long> resultList = query.getResultList();
    doSetPids(resultList);//w w w.ja v a  2s  .c  o  m
}

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

private Set<Long> addPredicateDate(String theParamName, Set<Long> thePids,
        List<? extends IQueryParameterType> theList) {
    if (theList == null || theList.isEmpty()) {
        return thePids;
    }//  ww w  .ja  va2s.  c o m

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

    List<Predicate> codePredicates = new ArrayList<Predicate>();
    for (IQueryParameterType nextOr : theList) {
        IQueryParameterType params = nextOr;
        Predicate p = createPredicateDate(builder, from, params);
        codePredicates.add(p);
    }

    Predicate masterCodePredicate = builder.or(codePredicates.toArray(new Predicate[0]));

    Predicate type = builder.equal(from.get("myResourceType"), myResourceName);
    Predicate name = builder.equal(from.get("myParamName"), theParamName);
    if (thePids.size() > 0) {
        Predicate inPids = (from.get("myResourcePid").in(thePids));
        cq.where(builder.and(type, name, masterCodePredicate, inPids));
    } else {
        cq.where(builder.and(type, name, masterCodePredicate));
    }

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

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

private Set<Long> addPredicateString(String theParamName, Set<Long> thePids,
        List<? extends IQueryParameterType> theList) {
    if (theList == null || theList.isEmpty()) {
        return thePids;
    }// w w  w  .  ja  v a 2 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;

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

    Predicate masterCodePredicate = builder.or(codePredicates.toArray(new Predicate[0]));

    Predicate type = builder.equal(from.get("myResourceType"), myResourceName);
    Predicate name = builder.equal(from.get("myParamName"), theParamName);
    if (thePids.size() > 0) {
        Predicate inPids = (from.get("myResourcePid").in(thePids));
        cq.where(builder.and(type, name, masterCodePredicate, inPids));
    } else {
        cq.where(builder.and(type, name, masterCodePredicate));
    }

    TypedQuery<Long> q = myEntityManager.createQuery(cq);
    return new HashSet<Long>(q.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));
    }/* www  . j  a v  a2 s . c  o  m*/

    cq.where(toArray(predicates));

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

From source file:fi.vm.sade.eperusteet.ylops.service.ops.impl.OpetussuunnitelmaServiceImpl.java

private CriteriaQuery<Opetussuunnitelma> getQuery(OpetussuunnitelmaQuery pquery) {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Opetussuunnitelma> query = builder.createQuery(Opetussuunnitelma.class);
    Root<Opetussuunnitelma> ops = query.from(Opetussuunnitelma.class);

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

    // VAIN JULKAISTUT
    ehdot.add(builder.equal(ops.get(Opetussuunnitelma_.tila), Tila.JULKAISTU));

    // Haettu organisaatio lytyy opsilta
    if (pquery.getOrganisaatio() != null) {
        Expression<Set<String>> organisaatiot = ops.get(Opetussuunnitelma_.organisaatiot);
        ehdot.add(builder.and(builder.isMember(pquery.getOrganisaatio(), organisaatiot)));
    }/*from   w  ww . jav a2 s . co m*/

    // Koulutustyyppi
    if (pquery.getKoulutustyyppi() != null) {
        ehdot.add(builder.and(builder.equal(ops.get(Opetussuunnitelma_.koulutustyyppi),
                KoulutusTyyppi.of(pquery.getKoulutustyyppi()))));
    }

    // Perusteen tyyppi
    if (pquery.getTyyppi() != null) {
        ehdot.add(builder.and(builder.equal(ops.get(Opetussuunnitelma_.tyyppi), pquery.getTyyppi())));
    }

    // Perusteen id
    if (pquery.getPerusteenId() != null) {
        Path<PerusteCache> cachedPeruste = ops.join(Opetussuunnitelma_.cachedPeruste);
        ehdot.add(builder
                .and(builder.equal(cachedPeruste.get(PerusteCache_.perusteId), pquery.getPerusteenId())));
    }

    // Perusteen diaarinumero
    if (pquery.getPerusteenDiaarinumero() != null) {
        ehdot.add(builder.and(builder.equal(ops.get(Opetussuunnitelma_.perusteenDiaarinumero),
                pquery.getPerusteenDiaarinumero())));
    }

    query.where(ehdot.toArray(new Predicate[ehdot.size()]));

    return query.select(ops);
}