List of usage examples for javax.persistence.criteria CriteriaBuilder equal
Predicate equal(Expression<?> x, Object y);
From source file:org.openmeetings.app.data.user.Usermanagement.java
/** * query for a list of users// w w w .java2 s . c o m * * @param users_id * @param user_level * @param start * @param max * @param orderby * @return */ public SearchResult<Users> getUsersList(long user_level, int start, int max, String orderby, boolean asc) { try { if (authLevelManagement.checkAdminLevel(user_level)) { SearchResult<Users> sresult = new SearchResult<Users>(); sresult.setObjectName(Users.class.getName()); sresult.setRecords(usersDao.selectMaxFromUsers()); // get all users CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Users> cq = cb.createQuery(Users.class); Root<Users> c = cq.from(Users.class); Predicate condition = cb.equal(c.get("deleted"), "false"); cq.where(condition); cq.distinct(asc); if (asc) { cq.orderBy(cb.asc(c.get(orderby))); } else { cq.orderBy(cb.desc(c.get(orderby))); } TypedQuery<Users> q = em.createQuery(cq); q.setFirstResult(start); q.setMaxResults(max); List<Users> ll = q.getResultList(); sresult.setResult(ll); return sresult; } } catch (Exception ex2) { log.error("[getUsersList] " + ex2); } return null; }
From source file:ca.uhn.fhir.jpa.dao.BaseHapiFhirDao.java
private void findMatchingTagIds(String theResourceName, IIdType theResourceId, Set<Long> tagIds, Class<? extends BaseTag> entityClass) { {//www.j ava 2 s .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
private Set<Long> addPredicateId(Set<Long> theExistingPids, Set<Long> thePids) { if (thePids == null || thePids.isEmpty()) { return Collections.emptySet(); }/* ww w .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:me.ineson.demo.service.utils.RestUtils.java
/** * @param where//from w w w. j av a2s .c o m * @param root * @param query * @param builder * @param translations * @return */ public static Predicate parseWhereClause(String where, Root<?> root, CriteriaQuery<?> query, CriteriaBuilder builder, Map<String, String> translations) { List<Predicate> predicates = new ArrayList<Predicate>(); for (String singleCriteria : new StrTokenizer(where, ",").getTokenList()) { if (StringUtils.isNotBlank(singleCriteria)) { int equalsIndex = singleCriteria.indexOf("="); if (equalsIndex > 0) { String fieldPath = singleCriteria.substring(0, equalsIndex); String value = singleCriteria.substring(equalsIndex + 1); if (translations != null && translations.containsKey(fieldPath)) { String newFieldPath = translations.get(fieldPath); log.debug("replacing field {} with {} ", fieldPath, newFieldPath); fieldPath = newFieldPath; } StrTokenizer tokenizer = new StrTokenizer(fieldPath, "."); javax.persistence.criteria.Path<?> expression = null; while (tokenizer.hasNext()) { String field = tokenizer.next(); if (tokenizer.hasNext()) { if (expression == null) { expression = root.join(field); } else { // expression = expression.join( field); throw new IllegalArgumentException( "Paths to joins of greater than a depth of 1 are not implemented yet"); } } else { if (expression == null) { log.info("expression0 {}", expression); expression = root.get(field); log.info("expression1 {}", expression); } else { expression = expression.get(field); } } } Object realValue = value; if ("bodyType".equals(fieldPath)) { me.ineson.demo.service.SolarBodyType solarBodyType = me.ineson.demo.service.SolarBodyType .valueOf(value); switch (solarBodyType) { case PLANET: realValue = SolarBodyType.Planet; break; case SUN: realValue = SolarBodyType.Sun; break; case DWARF_PLANET: realValue = SolarBodyType.DwarfPlanet; break; default: realValue = solarBodyType; } log.info("enum bodyType before {} after {}", value, realValue); } log.info("expression9 {}", expression); predicates.add(builder.equal(expression, realValue)); } } } log.debug("predictes "); if (predicates.size() == 0) { return null; } if (predicates.size() == 1) { return predicates.get(0); } return builder.and(predicates.toArray(new Predicate[predicates.size()])); }
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 www .java2s. com } 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 List<Predicate> createPredicateTagList(Path<TagDefinition> theDefJoin, CriteriaBuilder theBuilder, TagTypeEnum theTagType, List<Pair<String, String>> theTokens) { Predicate typePrediate = theBuilder.equal(theDefJoin.get("myTagType"), theTagType); List<Predicate> orPredicates = Lists.newArrayList(); for (Pair<String, String> next : theTokens) { Predicate codePrediate = theBuilder.equal(theDefJoin.get("myCode"), next.getRight()); if (isNotBlank(next.getLeft())) { Predicate systemPrediate = theBuilder.equal(theDefJoin.get("mySystem"), next.getLeft()); orPredicates.add(theBuilder.and(typePrediate, systemPrediate, codePrediate)); } else {// w w w. j a v a 2 s . c o m orPredicates.add(theBuilder.and(typePrediate, codePrediate)); } } return orPredicates; }
From source file:net.shopxx.dao.impl.StatisticDaoImpl.java
public List<Statistic> analyze(Statistic.Period period, Date beginDate, Date endDate) { Assert.notNull(period);/*from w w w . ja va2 s .c om*/ 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:ch.puzzle.itc.mobiliar.business.server.boundary.ServerView.java
public List<ServerTuple> getNodeServers(String hostFilter, String appServerFilter, String runtimeFilter, String nodeFilter, String contextFilter) { CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<ServerTuple> q = cb.createQuery(ServerTuple.class); //get Node ResType Root<ResourceEntity> node = q.from(ResourceEntity.class); Join<ResourceEntity, ResourceTypeEntity> nodeType = node.join("resourceType", JoinType.LEFT); Join<ResourceEntity, ReleaseEntity> nodeRelease = node.join("release", JoinType.LEFT); //get Props on node Join<ResourceEntity, ResourceContextEntity> resCtx = node.join("contexts", JoinType.LEFT); Join<ResourceContextEntity, ContextEntity> nodeCtx = resCtx.join("context", JoinType.LEFT); Join<ContextEntity, ContextEntity> nodeDomain = nodeCtx.join("parent", JoinType.LEFT); Join<ResourceContextEntity, PropertyEntity> nodeProp = resCtx.join("properties", JoinType.LEFT); Join<PropertyEntity, PropertyDescriptorEntity> nodePropType = nodeProp.join("descriptor", JoinType.LEFT); //get AppServer Join<ResourceEntity, ConsumedResourceRelationEntity> nodeResRel = node.join("consumedSlaveRelations", JoinType.LEFT);/*from www.j av a2 s . c o m*/ Join<ConsumedResourceRelationEntity, ResourceEntity> appServer = nodeResRel.join("masterResource", JoinType.LEFT); Join<ResourceEntity, ReleaseEntity> asRelease = appServer.join("release", JoinType.LEFT); Join<ResourceEntity, ResourceTypeEntity> asType = appServer.join("resourceType", JoinType.LEFT); //get Runtime of as Join<ResourceEntity, ConsumedResourceRelationEntity> asResRel = appServer.join("consumedMasterRelations", JoinType.LEFT); Join<ConsumedResourceRelationEntity, ResourceEntity> asRuntime = asResRel.join("slaveResource", JoinType.LEFT); Join<ResourceEntity, ResourceTypeEntity> runtimeType = asRuntime.join("resourceType", JoinType.LEFT); q.select(cb.construct(ServerTuple.class, nodeProp.get("value"), appServer.get("name"), appServer.get("id"), asRelease.get("name"), asRuntime.get("name"), node.get("name"), node.get("id"), nodeRelease.get("name"), nodeDomain.get("name"), nodeDomain.get("id"), nodeCtx.get("name"), nodeCtx.get("id"), cb.literal(1) // true )); Predicate p = cb.and(cb.equal(nodeType.get("name"), DefaultResourceTypeDefinition.NODE.name()), cb.or(cb.equal(asType.get("name"), DefaultResourceTypeDefinition.APPLICATIONSERVER.name()), cb.isNull(asType.get("name")) //nodes without appServer ), cb.or(cb.equal(runtimeType.get("name"), ResourceTypeEntity.RUNTIME), cb.isNull(runtimeType.get("name"))), cb.isNotNull(nodeProp.get("value")), cb.equal(nodePropType.get("propertyName"), "hostName") ); p = addFilters(p, cb, hostFilter, appServerFilter, runtimeFilter, nodeFilter, contextFilter, nodeProp.<String>get("value"), appServer.<String>get("name"), asRuntime.<String>get("name"), node.<String>get("name"), nodeCtx.<String>get("name")); q.where(p); TypedQuery<ServerTuple> query = entityManager.createQuery(q); List<ServerTuple> servers = query.getResultList(); return servers; }
From source file:net.awired.generic.jpa.dao.impl.GenericDaoImpl.java
private Predicate[] BuildFilterPredicates(Root<ENTITY> root, String search, List<String> searchProperties) { if (Strings.isNullOrEmpty(search)) { return new Predicate[] {}; }/* w ww .j a v a2s. c o m*/ CriteriaBuilder builder = entityManager.getCriteriaBuilder(); EntityType<ENTITY> type = entityManager.getMetamodel().entity(entityClass); String[] split = search.split(","); Set<SingularAttribute<? super ENTITY, ?>> attributes = type.getSingularAttributes(); List<Predicate> predicates = new ArrayList<Predicate>(split.length * attributes.size()); for (String searchElem : split) { String searchProperty = null; if (searchElem.contains(":")) { String[] propSearchs = searchElem.trim().split(":", 2); searchElem = propSearchs[1]; searchProperty = propSearchs[0]; } boolean numeric; try { Double.parseDouble(searchElem); numeric = true; } catch (Exception e) { numeric = false; } for (SingularAttribute<? super ENTITY, ?> attribute : attributes) { if (searchProperties != null && !searchProperties.isEmpty() && !searchProperties.contains(attribute.getName())) { continue; // skip this property as its not listed in searchable properties } if (searchProperty != null && !searchProperty.equals(attribute.getName())) { continue; // skip this property as we are searching for specific property } Class<?> javaType = attribute.getJavaType(); if (javaType == String.class) { @SuppressWarnings("unchecked") Predicate like = builder.like( builder.lower(root.get((SingularAttribute<ENTITY, String>) attribute)), "%" + searchElem.toLowerCase().trim() + "%"); predicates.add(like); } else if (numeric && (Number.class.isAssignableFrom(javaType) || javaType == int.class || javaType == short.class || javaType == long.class || javaType == float.class || javaType == double.class || javaType == byte.class)) { Predicate like = builder.equal(root.get(attribute), searchElem.toLowerCase().trim()); predicates.add(like); } //TODO fancy types // enums // char // boolean } } return predicates.toArray(new Predicate[] {}); }
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; }//from w w w . ja v a2s.com 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()); }