List of usage examples for javax.persistence.criteria CriteriaQuery multiselect
CriteriaQuery<T> multiselect(List<Selection<?>> selectionList);
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 w ww. j a va 2 s .c om * @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:edu.sabanciuniv.sentilab.sare.controllers.entitymanagers.PersistentDocumentStoreController.java
/** * Gets all UUIDs for {@code T} type document stores owned by the given owner. * @param em the {@link EntityManager} to use. * @param ownerId the ID of the owner.// w w w . j a va 2 s. c o m * @param entityClass the specific type of document stores to be retrieved; must be annotated with the {@link Entity} annotation. * @return a {@link List} containing {@link String} representations of the UUIDs. */ public <T extends PersistentDocumentStore> List<String> getAllUuids(EntityManager em, String ownerId, Class<T> entityClass) { Validate.notNull(em, CannedMessages.NULL_ARGUMENT, "em"); Validate.notNull(ownerId, CannedMessages.NULL_ARGUMENT, "ownerId"); Validate.notNull(entityClass, CannedMessages.NULL_ARGUMENT, "entityClass"); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<byte[]> cq = cb.createQuery(byte[].class); Root<T> store = cq.from(entityClass); cq.multiselect(store.get("id")) .where(cb.equal(store.get("ownerId"), cb.parameter(String.class, "ownerId"))); TypedQuery<byte[]> tq = em.createQuery(cq); tq.setParameter("ownerId", ownerId); return Lists.newArrayList(Iterables.transform(tq.getResultList(), UuidUtils.uuidBytesToStringFunction())); }
From source file:eu.uqasar.service.ProductService.java
public List fillVersionDropDownChoice() { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Product> criteria = cb.createQuery(Product.class); Root<Product> from = criteria.from(Product.class); criteria.multiselect(from.get(Product_.version)); return (List) em.createQuery(criteria).getResultList(); }
From source file:edu.sabanciuniv.sentilab.sare.models.base.documentStore.PersistentDocumentStore.java
/** * Gets identifiers of documents in this store. * @param em the {@link EntityManager} to get the documents from. * @return an {@link Iterable} of document identifiers. *//* w ww . j a v a2 s . co m*/ public Iterable<byte[]> getDocumentIds(EntityManager em) { Validate.notNull(em, CannedMessages.NULL_ARGUMENT, "em"); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<byte[]> cq = cb.createQuery(byte[].class); Root<PersistentDocument> doc = cq.from(PersistentDocument.class); cq.multiselect(doc.get("id")) .where(cb.equal(doc.get("store"), cb.parameter(PersistentDocumentStore.class, "store"))); TypedQuery<byte[]> tq = em.createQuery(cq); tq.setParameter("store", this); return tq.getResultList(); }
From source file:bq.jpa.demo.query.criteria.service.CriteriaService.java
/** * use customize object in select//w ww.j a v a 2 s . c o m */ public void doSelect3() { CriteriaBuilder cb = em.getCriteriaBuilder(); // return type is a customized object CriteriaQuery<EmployeeBasicInfo> c = cb.createQuery(EmployeeBasicInfo.class); Root<Employee> e = c.from(Employee.class); // method 1 : must use multiple select, cannot use select method, because of strong type check c.multiselect(e.get("name")); showResult(c); // method 2 : use select and cb.construct c.select(cb.construct(EmployeeBasicInfo.class, e.get("name"))); showResult(c); // method 3 : use multiple select and cb.construct // NOTE : UNSUPPORT! // CriteriaQuery<EmployeeBasicInfo> c2 = cb.createQuery(EmployeeBasicInfo.class); // Root<Employee> e2 = c2.from(Employee.class); // c2.multiselect(cb.construct(EmployeeBasicInfo.class, e2.get("name"))); // showResult(c2); }
From source file:com.adeptj.modules.data.jpa.core.AbstractJpaRepository.java
/** * {@inheritDoc}// w w w .ja v a 2 s . co m */ @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.j a v a 2 s .com*/ 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 . ja va 2s . 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:com.deloitte.smt.service.SignalDetectionService.java
@SuppressWarnings({ "unchecked", "rawtypes" }) public SmtResponse findAllForSearch(SearchDto searchDto) { CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(); Root<SignalDetection> rootSignalDetection = criteriaQuery.from(SignalDetection.class); Join<SignalDetection, TopicSignalDetectionAssignmentAssignees> joinDetectionAssignees = rootSignalDetection .join("topicSignalDetectionAssignmentAssignees", JoinType.LEFT); //left outer join if (null != searchDto) { Root<Ingredient> rootIngredient = criteriaQuery.from(Ingredient.class); List<Predicate> predicates = new ArrayList<>(10); predicates.add(criteriaBuilder.equal(rootSignalDetection.get("id"), rootIngredient.get(SmtConstant.DETECTION_ID.getDescription()))); addDescription(searchDto, criteriaBuilder, rootSignalDetection, predicates); addFrequency(searchDto, criteriaBuilder, rootSignalDetection, predicates); addIngredients(searchDto, criteriaBuilder, rootIngredient, predicates); addProducts(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates); addLicenses(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates); addSocs(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates); addHlts(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates); addHlgts(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates); addPts(searchDto, criteriaBuilder, criteriaQuery, rootSignalDetection, predicates); addCreatedOrLastRunDate(searchDto, criteriaBuilder, rootSignalDetection, predicates); /**TopicSignalValidationAssignmentAssignees **/ addUserGroupKeys(searchDto, criteriaBuilder, joinDetectionAssignees, rootSignalDetection, predicates); Predicate andPredicate = criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])); criteriaQuery.multiselect(rootSignalDetection).where(andPredicate) .orderBy(criteriaBuilder .desc(rootSignalDetection.get(SmtConstant.CREATED_DATE.getDescription()))) .distinct(true);//from w w w . ja va2 s . c o m } else { criteriaQuery.multiselect(rootSignalDetection) .orderBy(criteriaBuilder .desc(rootSignalDetection.get(SmtConstant.CREATED_DATE.getDescription()))) .distinct(true); } SmtResponse smtResponse = new SmtResponse(); TypedQuery<SignalDetection> q = entityManager.createQuery(criteriaQuery); if (!CollectionUtils.isEmpty(q.getResultList())) { smtResponse.setTotalRecords(q.getResultList().size()); } if (searchDto != null && searchDto.getFetchSize() != 0) { q.setFirstResult(searchDto.getFromRecord()); q.setMaxResults(searchDto.getFetchSize()); smtResponse.setFetchSize(searchDto.getFetchSize()); smtResponse.setFromRecord(searchDto.getFromRecord()); } smtResponse.setResult(q.getResultList()); if (!CollectionUtils.isEmpty(smtResponse.getResult())) { List<SignalDetection> result = (List<SignalDetection>) smtResponse.getResult(); for (SignalDetection signalDetection : result) { signalDetection.setDenominatorForPoisson( denominatorForPoissonRepository.findByDetectionId(signalDetection.getId())); } } return smtResponse; }
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 w ww. j ava 2 s . c o m 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); } } }