List of usage examples for javax.persistence.criteria CriteriaQuery select
CriteriaQuery<T> select(Selection<? extends T> selection);
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/* w ww.j a v 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.SearchBuilder.java
private void addPredicateReference(String theParamName, List<? extends IQueryParameterType> theList) { assert theParamName.contains(".") == false; if (Boolean.TRUE.equals(theList.get(0).getMissing())) { addPredicateParamMissingResourceLink("myResourceLinks", theParamName); return;/*from w ww . j a v a2 s . c om*/ } CriteriaBuilder builder = myEntityManager.getCriteriaBuilder(); CriteriaQuery<Long> cq = builder.createQuery(Long.class); Root<ResourceLink> from = cq.from(ResourceLink.class); cq.select(from.get("mySourceResourcePid").as(Long.class)); List<Predicate> codePredicates = new ArrayList<Predicate>(); for (IQueryParameterType nextOr : theList) { IQueryParameterType params = nextOr; if (addPredicateMissingFalseIfPresentForResourceLink(builder, theParamName, from, codePredicates, nextOr)) { continue; } if (params instanceof ReferenceParam) { ReferenceParam ref = (ReferenceParam) params; if (isBlank(ref.getChain())) { IIdType dt = new IdDt(ref.getBaseUrl(), ref.getResourceType(), ref.getIdPart(), null); if (dt.hasBaseUrl()) { if (myCallingDao.getConfig().getTreatBaseUrlsAsLocal().contains(dt.getBaseUrl())) { dt = dt.toUnqualified(); } else { ourLog.debug("Searching for resource link with target URL: {}", dt.getValue()); Predicate eq = builder.equal(from.get("myTargetResourceUrl"), dt.getValue()); codePredicates.add(eq); continue; } } List<Long> targetPid; try { targetPid = myCallingDao.translateForcedIdToPids(dt); } catch (ResourceNotFoundException e) { doSetPids(new ArrayList<Long>()); return; } for (Long next : targetPid) { ourLog.debug("Searching for resource link with target PID: {}", next); Predicate eq = builder.equal(from.get("myTargetResourcePid"), next); codePredicates.add(eq); } } else { List<Class<? extends IBaseResource>> resourceTypes; String resourceId; if (!ref.getValue().matches("[a-zA-Z]+\\/.*")) { String paramPath = myContext.getResourceDefinition(myResourceType) .getSearchParam(theParamName).getPath(); if (paramPath.endsWith(".as(Reference)")) { paramPath = paramPath.substring(0, paramPath.length() - ".as(Reference)".length()) + "Reference"; } BaseRuntimeChildDefinition def = myContext.newTerser().getDefinition(myResourceType, paramPath); if (def instanceof RuntimeChildChoiceDefinition) { RuntimeChildChoiceDefinition choiceDef = (RuntimeChildChoiceDefinition) def; resourceTypes = choiceDef.getResourceTypes(); } else if (def instanceof RuntimeChildResourceDefinition) { RuntimeChildResourceDefinition resDef = (RuntimeChildResourceDefinition) def; resourceTypes = resDef.getResourceTypes(); } else { throw new ConfigurationException("Property " + paramPath + " of type " + myResourceName + " is not a resource: " + def.getClass()); } resourceId = ref.getValue(); } else { RuntimeResourceDefinition resDef = myContext.getResourceDefinition(ref.getResourceType()); resourceTypes = new ArrayList<Class<? extends IBaseResource>>(1); resourceTypes.add(resDef.getImplementingClass()); resourceId = ref.getIdPart(); } boolean foundChainMatch = false; String chain = ref.getChain(); String remainingChain = null; int chainDotIndex = chain.indexOf('.'); if (chainDotIndex != -1) { remainingChain = chain.substring(chainDotIndex + 1); chain = chain.substring(0, chainDotIndex); } for (Class<? extends IBaseResource> nextType : resourceTypes) { RuntimeResourceDefinition typeDef = myContext.getResourceDefinition(nextType); IFhirResourceDao<?> dao = myCallingDao.getDao(nextType); if (dao == null) { ourLog.debug("Don't have a DAO for type {}", nextType.getSimpleName()); continue; } int qualifierIndex = chain.indexOf(':'); String qualifier = null; if (qualifierIndex != -1) { qualifier = chain.substring(qualifierIndex); chain = chain.substring(0, qualifierIndex); } boolean isMeta = BaseHapiFhirDao.RESOURCE_META_PARAMS.containsKey(chain); RuntimeSearchParam param = null; if (!isMeta) { param = typeDef.getSearchParam(chain); if (param == null) { ourLog.debug("Type {} doesn't have search param {}", nextType.getSimpleName(), param); continue; } } IQueryParameterType chainValue; if (remainingChain != null) { if (param == null || param.getParamType() != RestSearchParameterTypeEnum.REFERENCE) { ourLog.debug("Type {} parameter {} is not a reference, can not chain {}", new Object[] { nextType.getSimpleName(), chain, remainingChain }); continue; } chainValue = new ReferenceParam(); chainValue.setValueAsQueryToken(myContext, theParamName, qualifier, resourceId); ((ReferenceParam) chainValue).setChain(remainingChain); } else if (isMeta) { IQueryParameterType type = BaseHapiFhirDao.newInstanceType(chain); type.setValueAsQueryToken(myContext, theParamName, qualifier, resourceId); chainValue = type; } else { chainValue = toParameterType(param, qualifier, resourceId); } foundChainMatch = true; Set<Long> pids = dao.searchForIds(chain, chainValue); if (pids.isEmpty()) { continue; } Predicate eq = from.get("myTargetResourcePid").in(pids); codePredicates.add(eq); } if (!foundChainMatch) { throw new InvalidRequestException( myContext.getLocalizer().getMessage(BaseHapiFhirResourceDao.class, "invalidParameterChain", theParamName + '.' + ref.getChain())); } } } else { throw new IllegalArgumentException( "Invalid token type (expecting ReferenceParam): " + params.getClass()); } } List<Predicate> predicates = new ArrayList<Predicate>(); predicates.add(createResourceLinkPathPredicate(theParamName, from)); predicates.add(builder.or(toArray(codePredicates))); createPredicateResourceId(builder, cq, predicates, from.get("mySourceResourcePid").as(Long.class)); createPredicateLastUpdatedForResourceLink(builder, from, predicates); cq.where(builder.and(toArray(predicates))); TypedQuery<Long> q = myEntityManager.createQuery(cq); doSetPids(new HashSet<Long>(q.getResultList())); }
From source file:gov.osti.services.Metadata.java
/** * Acquire a List of records in pending ("Submitted") state, to be approved * for indexing and searching.//from w w w . ja v a 2 s . co m * * JSON response is of the form: * * {"records":[{"code_id":n, ...} ], * "start":0, "rows":20, "total":100} * * Where records is an array of DOECodeMetadata JSON, start is the beginning * row number, rows is the number requested (or total if less available), * and total is the total number of rows matching the filter. * * Return Codes: * 200 - OK, JSON is returned as above * 401 - Unauthorized, login is required * 403 - Forbidden, insufficient privileges (role required) * 500 - unexpected error * * @param start the starting row number (from 0) * @param rows number of rows desired (0 is unlimited) * @param siteCode (optional) a SITE OWNERSHIP CODE to filter by site * @param state the WORKFLOW STATE if desired (default Submitted and Announced). One of * Approved, Saved, Submitted, or Announced, if supplied. * @return JSON of a records response */ @GET @Path("/projects/pending") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RequiresAuthentication @RequiresRoles("OSTI") public Response listProjectsPending(@QueryParam("start") int start, @QueryParam("rows") int rows, @QueryParam("site") String siteCode, @QueryParam("state") String state) { EntityManager em = DoeServletContextListener.createEntityManager(); try { // get a JPA CriteriaBuilder instance CriteriaBuilder cb = em.getCriteriaBuilder(); // create a CriteriaQuery for the COUNT CriteriaQuery<Long> countQuery = cb.createQuery(Long.class); Root<DOECodeMetadata> md = countQuery.from(DOECodeMetadata.class); countQuery.select(cb.count(md)); Expression<String> workflowStatus = md.get("workflowStatus"); Expression<String> siteOwnershipCode = md.get("siteOwnershipCode"); // default requested STATE; take Submitted and Announced as the default values if not supplied List<DOECodeMetadata.Status> requestedStates = new ArrayList(); String queryState = (StringUtils.isEmpty(state)) ? "" : state.toLowerCase(); switch (queryState) { case "approved": requestedStates.add(DOECodeMetadata.Status.Approved); break; case "saved": requestedStates.add(DOECodeMetadata.Status.Saved); break; case "submitted": requestedStates.add(DOECodeMetadata.Status.Submitted); break; case "announced": requestedStates.add(DOECodeMetadata.Status.Announced); break; default: requestedStates.add(DOECodeMetadata.Status.Submitted); requestedStates.add(DOECodeMetadata.Status.Announced); break; } Predicate statusPredicate = workflowStatus.in(requestedStates); ParameterExpression<String> site = cb.parameter(String.class, "site"); if (null == siteCode) { countQuery.where(statusPredicate); } else { countQuery.where(cb.and(statusPredicate, cb.equal(siteOwnershipCode, site))); } // query for the COUNT TypedQuery<Long> cq = em.createQuery(countQuery); cq.setParameter("status", requestedStates); if (null != siteCode) cq.setParameter("site", siteCode); long rowCount = cq.getSingleResult(); // rows count should be less than 100 for pagination; 0 is a special case rows = (rows > 100) ? 100 : rows; // create a CriteriaQuery for the ROWS CriteriaQuery<DOECodeMetadata> rowQuery = cb.createQuery(DOECodeMetadata.class); rowQuery.select(md); if (null == siteCode) { rowQuery.where(statusPredicate); } else { rowQuery.where(cb.and(statusPredicate, cb.equal(siteOwnershipCode, site))); } TypedQuery<DOECodeMetadata> rq = em.createQuery(rowQuery); rq.setParameter("status", requestedStates); if (null != siteCode) rq.setParameter("site", siteCode); rq.setFirstResult(start); if (0 != rows) rq.setMaxResults(rows); RecordsList records = new RecordsList(rq.getResultList()); records.setTotal(rowCount); records.setStart(start); return Response.ok().entity(mapper.valueToTree(records).toString()).build(); } finally { em.close(); } }
From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java
private void addPredicateTag(List<List<? extends IQueryParameterType>> theList, String theParamName, DateRangeParam theLastUpdated) { TagTypeEnum tagType;/*from w w w .java 2 s . com*/ if (Constants.PARAM_TAG.equals(theParamName)) { tagType = TagTypeEnum.TAG; } else if (Constants.PARAM_PROFILE.equals(theParamName)) { tagType = TagTypeEnum.PROFILE; } else if (Constants.PARAM_SECURITY.equals(theParamName)) { tagType = TagTypeEnum.SECURITY_LABEL; } else { throw new IllegalArgumentException("Param name: " + theParamName); // shouldn't happen } /* * 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)); */ List<Pair<String, String>> notTags = Lists.newArrayList(); for (List<? extends IQueryParameterType> nextAndParams : theList) { for (IQueryParameterType nextOrParams : nextAndParams) { if (nextOrParams instanceof TokenParam) { TokenParam param = (TokenParam) nextOrParams; if (param.getModifier() == TokenParamModifier.NOT) { if (isNotBlank(param.getSystem()) || isNotBlank(param.getValue())) { notTags.add(Pair.of(param.getSystem(), param.getValue())); } } } } } /* * We have a parameter of ResourceType?_tag:not=foo This means match resources that don't have the given tag(s) */ if (notTags.isEmpty() == false) { // 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<ResourceTag> subQfrom = subQ.from(ResourceTag.class); // subQ.select(subQfrom.get("myResourceId").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)); } for (List<? extends IQueryParameterType> nextAndParams : theList) { boolean haveTags = false; for (IQueryParameterType nextParamUncasted : nextAndParams) { if (nextParamUncasted instanceof TokenParam) { TokenParam nextParam = (TokenParam) nextParamUncasted; if (isNotBlank(nextParam.getValue())) { haveTags = true; } else if (isNotBlank(nextParam.getSystem())) { throw new InvalidRequestException("Invalid " + theParamName + " parameter (must supply a value/code and not just a system): " + nextParam.getValueAsQueryToken(myContext)); } } else { UriParam nextParam = (UriParam) nextParamUncasted; if (isNotBlank(nextParam.getValue())) { haveTags = true; } } } if (!haveTags) { continue; } CriteriaBuilder builder = myEntityManager.getCriteriaBuilder(); boolean paramInverted = false; List<Pair<String, String>> tokens = Lists.newArrayList(); for (IQueryParameterType nextOrParams : nextAndParams) { String code; String system; if (nextOrParams instanceof TokenParam) { TokenParam nextParam = (TokenParam) nextOrParams; code = nextParam.getValue(); system = nextParam.getSystem(); if (nextParam.getModifier() == TokenParamModifier.NOT) { paramInverted = true; } } else { UriParam nextParam = (UriParam) nextOrParams; code = nextParam.getValue(); system = null; } if (isNotBlank(code)) { tokens.add(Pair.of(system, code)); } } if (tokens.isEmpty()) { continue; } if (paramInverted) { ourLog.debug("Searching for _tag:not"); CriteriaQuery<Long> cq = builder.createQuery(Long.class); Root<ResourceTable> newFrom = cq.from(ResourceTable.class); Subquery<Long> subQ = cq.subquery(Long.class); Root<ResourceTag> subQfrom = subQ.from(ResourceTag.class); subQ.select(subQfrom.get("myResourceId").as(Long.class)); cq.select(newFrom.get("myId").as(Long.class)); List<Predicate> andPredicates = new ArrayList<Predicate>(); andPredicates = new ArrayList<Predicate>(); andPredicates.add(builder.equal(newFrom.get("myResourceType"), myResourceName)); andPredicates.add(builder.not(builder.in(newFrom.get("myId")).value(subQ))); Subquery<Long> defJoin = subQ.subquery(Long.class); Root<TagDefinition> defJoinFrom = defJoin.from(TagDefinition.class); defJoin.select(defJoinFrom.get("myId").as(Long.class)); subQ.where(subQfrom.get("myTagId").as(Long.class).in(defJoin)); List<Predicate> orPredicates = createPredicateTagList(defJoinFrom, builder, tagType, tokens); defJoin.where(toArray(orPredicates)); cq.where(toArray(andPredicates)); TypedQuery<Long> q = myEntityManager.createQuery(cq); Set<Long> pids = new HashSet<Long>(q.getResultList()); doSetPids(pids); continue; } CriteriaQuery<Long> cq = builder.createQuery(Long.class); Root<ResourceTag> from = cq.from(ResourceTag.class); List<Predicate> andPredicates = new ArrayList<Predicate>(); andPredicates.add(builder.equal(from.get("myResourceType"), myResourceName)); From<ResourceTag, TagDefinition> defJoin = from.join("myTag"); Join<?, ResourceTable> defJoin2 = from.join("myResource"); Predicate notDeletedPredicatePrediate = builder.isNull(defJoin2.get("myDeleted")); andPredicates.add(notDeletedPredicatePrediate); List<Predicate> orPredicates = createPredicateTagList(defJoin, builder, tagType, tokens); andPredicates.add(builder.or(toArray(orPredicates))); if (theLastUpdated != null) { andPredicates.addAll(createLastUpdatedPredicates(theLastUpdated, builder, defJoin2)); } createPredicateResourceId(builder, cq, andPredicates, from.get("myResourceId").as(Long.class)); Predicate masterCodePredicate = builder.and(toArray(andPredicates)); cq.select(from.get("myResourceId").as(Long.class)); cq.where(masterCodePredicate); TypedQuery<Long> q = myEntityManager.createQuery(cq); Set<Long> pids = new HashSet<Long>(q.getResultList()); doSetPids(pids); } }
From source file:org.finra.dm.dao.AbstractDaoTest.java
/** * Returns a list of {@link EmrClusterCreationLogEntity} objects for the given cluster namespace, cluster definition name, and EMR cluster name. All the * given parameters are case insensitive. The returned list's order is not guaranteed. * * @param namespace - EMR cluster namespace * @param definitionName - EMR cluster definition name * @param clusterName - EMR cluster name * * @return list of EMR cluster creation logs *//*ww w .j a v a 2s.c o m*/ public List<EmrClusterCreationLogEntity> getEmrClusterCreationLogEntities(String namespace, String definitionName, String clusterName) { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<EmrClusterCreationLogEntity> query = builder.createQuery(EmrClusterCreationLogEntity.class); Root<EmrClusterCreationLogEntity> emrClusterCreationLogEntity = query .from(EmrClusterCreationLogEntity.class); Join<?, NamespaceEntity> namespaceEntity = emrClusterCreationLogEntity .join(EmrClusterCreationLogEntity_.namespace); Predicate namespacePredicate = builder.equal(builder.upper(namespaceEntity.get(NamespaceEntity_.code)), namespace.toUpperCase()); Predicate definitionNamePredicate = builder.equal( builder.upper( emrClusterCreationLogEntity.get(EmrClusterCreationLogEntity_.emrClusterDefinitionName)), definitionName.toUpperCase()); Predicate clusterNamePredicate = builder.equal( builder.upper(emrClusterCreationLogEntity.get(EmrClusterCreationLogEntity_.emrClusterName)), clusterName.toUpperCase()); query.select(emrClusterCreationLogEntity) .where(builder.and(namespacePredicate, definitionNamePredicate, clusterNamePredicate)); return entityManager.createQuery(query).getResultList(); }
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))); }// w w w. jav a 2 s .c om // 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); }
From source file:org.finra.dm.dao.impl.DmDaoImpl.java
private Timestamp getCurrentTimestamp() { // Create the criteria builder and the criteria. CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<Timestamp> criteria = builder.createQuery(Timestamp.class); // Add the clauses for the query. criteria.select(builder.currentTimestamp()).from(ConfigurationEntity.class); return entityManager.createQuery(criteria).getSingleResult(); }
From source file:org.finra.dm.dao.impl.DmDaoImpl.java
/** * {@inheritDoc}//from w w w.java 2s. c om */ @Override public JmsMessageEntity getOldestJmsMessage() { // Create the criteria builder and the criteria. CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<JmsMessageEntity> criteria = builder.createQuery(JmsMessageEntity.class); // The criteria root is the jms message. Root<JmsMessageEntity> jmsMessageEntity = criteria.from(JmsMessageEntity.class); // Add the select clause. criteria.select(jmsMessageEntity); // Add the order by clause, since we want to return only the oldest JMS message (a message with the smallest sequence generated id). criteria.orderBy(builder.asc(jmsMessageEntity.get(JmsMessageEntity_.id))); // Execute the query and ask it to return only the first row. List<JmsMessageEntity> resultList = entityManager.createQuery(criteria).setMaxResults(1).getResultList(); // Return the result. return resultList.size() > 0 ? resultList.get(0) : null; }
From source file:org.finra.dm.dao.impl.DmDaoImpl.java
/** * {@inheritDoc}/*w ww . jav a 2s .c o m*/ */ @Override public List<PartitionKeyGroupKey> getPartitionKeyGroups() { // Create the criteria builder and the criteria. CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<PartitionKeyGroupEntity> criteria = builder.createQuery(PartitionKeyGroupEntity.class); // The criteria root is the partition key group. Root<PartitionKeyGroupEntity> partitionKeyGroupEntity = criteria.from(PartitionKeyGroupEntity.class); criteria.select(partitionKeyGroupEntity); List<PartitionKeyGroupKey> partitionKeyGroupKeys = new ArrayList<>(); for (PartitionKeyGroupEntity entity : entityManager.createQuery(criteria).getResultList()) { PartitionKeyGroupKey partitionKeyGroupKey = new PartitionKeyGroupKey(); partitionKeyGroupKey.setPartitionKeyGroupName(entity.getPartitionKeyGroupName()); partitionKeyGroupKeys.add(partitionKeyGroupKey); } return partitionKeyGroupKeys; }
From source file:org.finra.dm.dao.impl.DmDaoImpl.java
/** * {@inheritDoc}// w w w .j av a 2 s .c om */ @Override public List<StorageKey> getStorages() { // Create the criteria builder and a tuple style criteria query. CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<String> criteria = builder.createQuery(String.class); // The criteria root is the storage. Root<StorageEntity> storageEntity = criteria.from(StorageEntity.class); // Get the columns. Path<String> storageNameColumn = storageEntity.get(StorageEntity_.name); // Add the select clause. criteria.select(storageNameColumn); // Add the order by clause. criteria.orderBy(builder.asc(storageNameColumn)); // Run the query to get a list of storage names back. List<String> storageNames = entityManager.createQuery(criteria).getResultList(); // Populate the "keys" objects from the returned storage names. List<StorageKey> storageKeys = new ArrayList<>(); for (String storageName : storageNames) { storageKeys.add(new StorageKey(storageName)); } return storageKeys; }