Example usage for javax.persistence.criteria CriteriaBuilder createTupleQuery

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

Introduction

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

Prototype

CriteriaQuery<Tuple> createTupleQuery();

Source Link

Document

Create a CriteriaQuery object that returns a tuple of objects as its result.

Usage

From source file:com.ocs.dynamo.dao.query.JpaQueryBuilder.java

/**
 * Creates a query for retrieving the IDs of the entities that match the provided filter
 * //from  ww  w .jav a 2 s.  c o m
 * @param entityManager
 *            the entity manager
 * @param entityClass
 *            the entity class
 * @param filter
 *            the filter to apply
 * @param sortOrder
 *            the sorting to apply
 * @return
 */
public static <T> CriteriaQuery<Tuple> createIdQuery(EntityManager entityManager, Class<T> entityClass,
        Filter filter, SortOrder... sortOrders) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> cq = builder.createTupleQuery();
    Root<T> root = cq.from(entityClass);

    // select only the ID
    cq.multiselect(root.get(DynamoConstants.ID));

    // Set where clause
    Predicate p = createPredicate(filter, builder, root);
    if (p != null) {
        cq.where(p);
    }

    // add order clause - this is also important in case of an ID query
    // since we do need to return the correct IDs!
    return addSortInformation(builder, cq, root, sortOrders);
}

From source file:hr.diskobolos.persistence.impl.EvaluationAnswerPersistenceImpl.java

@Override
public Map<MemberRegister, Integer> fetchTotalPointsPerMemberRegister(QuestionnaireType questionnaireType) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> cq = cb.createTupleQuery();
    Root<EvaluationAnswer> evaluationAnswer = cq.from(EvaluationAnswer.class);
    Join<EvaluationAnswer, QuestionChoicesDef> choiceDef = evaluationAnswer.join(EvaluationAnswer_.answer);
    Join<QuestionChoicesDef, EvaluationQuestionDef> questionDef = choiceDef
            .join(QuestionChoicesDef_.evaluationQuestionDef);
    ParameterExpression<QuestionnaireType> questionnaireTypeParam = cb.parameter(QuestionnaireType.class,
            "questionnaireType");
    Expression<Integer> value = evaluationAnswer.get(EvaluationAnswer_.answer).get(QuestionChoicesDef_.value)
            .as(Integer.class);
    cq.multiselect(evaluationAnswer.get(EvaluationAnswer_.memberRegister).alias("memberRegister"),
            value.alias("value"));
    cq.where(cb.equal(questionDef.get(EvaluationQuestionDef_.questionnaireType), questionnaireTypeParam));
    TypedQuery<Tuple> query = entityManager.createQuery(cq);
    query.setParameter("questionnaireType", questionnaireType);
    List<Tuple> result = query.getResultList();
    Map<MemberRegister, Integer> pointsPerMemberRegister = result.stream().collect(Collectors.groupingBy(t -> {
        return t.get("memberRegister", MemberRegister.class);
    }, Collectors.summingInt(t -> t.get("value", Integer.class))));

    return pointsPerMemberRegister;
}

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

@Override
public Map<String, Long> getResourceCounts() {
    CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> cq = builder.createTupleQuery();
    Root<?> from = cq.from(ResourceTable.class);
    cq.multiselect(from.get("myResourceType").as(String.class),
            builder.count(from.get("myResourceType")).as(Long.class));
    cq.groupBy(from.get("myResourceType"));

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

    Map<String, Long> retVal = new HashMap<String, Long>();
    for (Tuple next : q.getResultList()) {
        String resourceName = next.get(0, String.class);
        Long count = next.get(1, Long.class);
        retVal.put(resourceName, count);
    }/*  w ww. ja  v  a 2 s . c o m*/
    return retVal;
}

From source file:bq.jpa.demo.query.criteria.service.CriteriaService.java

/**
 * multiple select//  w  w  w .  j a  v a  2s .c o m
 */
public void doSelect2() {
    CriteriaBuilder cb = em.getCriteriaBuilder();

    // method1: tuple
    CriteriaQuery<Tuple> tupleQuery = cb.createTupleQuery();
    Root<Employee> e1 = tupleQuery.from(Employee.class);
    tupleQuery.select(cb.tuple(e1.get("id"), e1.get("name")));
    showResult(tupleQuery);

    // method2: object[] and criteriaquery.multiselec
    CriteriaQuery<Object[]> multiQuery = cb.createQuery(Object[].class);
    Root<Employee> e2 = multiQuery.from(Employee.class);
    multiQuery.multiselect(e2.get("id"), e2.get("name"));
    showResult(multiQuery);
}

From source file:com.adeptj.modules.data.jpa.core.AbstractJpaRepository.java

/**
 * {@inheritDoc}//from  ww  w  . j a v a2  s .com
 */
@Override
public <T extends BaseEntity> List<Tuple> findByTupleQuery(TupleQueryCriteria<T> criteria) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Tuple> cq = cb.createTupleQuery();
        Root<T> root = cq.from(criteria.getEntity());
        return em
                .createQuery(cq
                        .multiselect(criteria.getSelections().stream().map(root::get).toArray(Selection[]::new))
                        .where(cb.and(Predicates.from(criteria.getCriteriaAttributes(), cb, root))))
                .getResultList();
    } catch (Exception ex) { // NOSONAR
        throw new JpaException(ex);
    } finally {
        JpaUtil.closeEntityManager(em);
    }
}

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

private void findMatchingTagIds(String theResourceName, IIdType theResourceId, Set<Long> tagIds,
        Class<? extends BaseTag> entityClass) {
    {//from  w ww.java2s.  c om
        CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
        CriteriaQuery<Tuple> cq = builder.createTupleQuery();
        Root<? extends BaseTag> from = cq.from(entityClass);
        cq.multiselect(from.get("myTagId").as(Long.class)).distinct(true);

        if (theResourceName != null) {
            Predicate typePredicate = builder.equal(from.get("myResourceType"), theResourceName);
            if (theResourceId != null) {
                cq.where(typePredicate, builder.equal(from.get("myResourceId"),
                        translateForcedIdToPid(theResourceName, theResourceId.getIdPart())));
            } else {
                cq.where(typePredicate);
            }
        }

        TypedQuery<Tuple> query = myEntityManager.createQuery(cq);
        for (Tuple next : query.getResultList()) {
            tagIds.add(next.get(0, Long.class));
        }
    }
}

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));
        }//from  w  w w  . j av  a2 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:ca.uhn.fhir.jpa.dao.SearchBuilder.java

private void processSort(final SearchParameterMap theParams) {

    // Set<Long> loadPids = theLoadPids;
    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);

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

        createSort(builder, from, theParams.getSort(), orders, predicates);

        if (orders.size() > 0) {

            // TODO: why do we need the existing list for this join to work?
            Collection<Long> originalPids = doGetPids();

            LinkedHashSet<Long> loadPids = new LinkedHashSet<Long>();
            cq.multiselect(from.get("myId").as(Long.class));
            cq.where(toArray(predicates));
            cq.orderBy(orders);/*from   ww  w .j  av  a  2  s. c  om*/

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

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

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

            ArrayList<Long> 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);
                }
            }

            doSetPids(pids);
        }
    }

}

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

public IBundleProvider search(final SearchParameterMap theParams) {
    myParams = theParams;/*from  www . j a v a  2  s. c o  m*/
    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:org.apache.ambari.server.orm.dao.ServiceConfigDAO.java

@RequiresSession
public List<ServiceConfigEntity> getLastServiceConfigVersionsForGroups(Collection<Long> configGroupIds) {
    if (configGroupIds == null || configGroupIds.isEmpty()) {
        return Collections.emptyList();
    }/*from   w  w  w  .  j  a v  a  2  s .c  o m*/
    CriteriaBuilder cb = entityManagerProvider.get().getCriteriaBuilder();
    CriteriaQuery<Tuple> cq = cb.createTupleQuery();
    Root<ServiceConfigEntity> groupVersion = cq.from(ServiceConfigEntity.class);

    cq.multiselect(groupVersion.get("groupId").alias("groupId"),
            cb.max(groupVersion.<Long>get("version")).alias("lastVersion"));
    cq.where(groupVersion.get("groupId").in(configGroupIds));
    cq.groupBy(groupVersion.get("groupId"));
    List<Tuple> tuples = daoUtils.selectList(entityManagerProvider.get().createQuery(cq));
    List<ServiceConfigEntity> result = new ArrayList<ServiceConfigEntity>();
    //subquery look to be very poor, no bulk select then, cache should help here as result size is naturally limited
    for (Tuple tuple : tuples) {
        CriteriaQuery<ServiceConfigEntity> sce = cb.createQuery(ServiceConfigEntity.class);
        Root<ServiceConfigEntity> sceRoot = sce.from(ServiceConfigEntity.class);

        sce.where(cb.and(cb.equal(sceRoot.get("groupId"), tuple.get("groupId")),
                cb.equal(sceRoot.get("version"), tuple.get("lastVersion"))));
        sce.select(sceRoot);
        result.add(daoUtils.selectSingle(entityManagerProvider.get().createQuery(sce)));
    }

    return result;
}