List of usage examples for javax.persistence.criteria Root join
<Y> Join<X, Y> join(SingularAttribute<? super X, Y> attribute);
From source file:net.shopxx.dao.impl.ArticleDaoImpl.java
public Page<Article> findPage(ArticleCategory articleCategory, Tag tag, Boolean isPublication, Pageable pageable) {//from w w w .ja va 2 s. co m CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<Article> criteriaQuery = criteriaBuilder.createQuery(Article.class); Root<Article> root = criteriaQuery.from(Article.class); criteriaQuery.select(root); Predicate restrictions = criteriaBuilder.conjunction(); if (articleCategory != null) { Subquery<ArticleCategory> subquery = criteriaQuery.subquery(ArticleCategory.class); Root<ArticleCategory> subqueryRoot = subquery.from(ArticleCategory.class); subquery.select(subqueryRoot); subquery.where(criteriaBuilder.or(criteriaBuilder.equal(subqueryRoot, articleCategory), criteriaBuilder.like(subqueryRoot.<String>get("treePath"), "%" + ArticleCategory.TREE_PATH_SEPARATOR + articleCategory.getId() + ArticleCategory.TREE_PATH_SEPARATOR + "%"))); restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.in(root.get("articleCategory")).value(subquery)); } if (tag != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.join("tags"), tag)); } if (isPublication != null) { restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isPublication"), isPublication)); } criteriaQuery.where(restrictions); if (pageable == null || ((StringUtils.isEmpty(pageable.getOrderProperty()) || pageable.getOrderDirection() == null) && CollectionUtils.isEmpty(pageable.getOrders()))) { criteriaQuery.orderBy(criteriaBuilder.desc(root.get("isTop")), criteriaBuilder.desc(root.get("createDate"))); } return super.findPage(criteriaQuery, pageable); }
From source file:de.hopmann.msc.slave.service.PackageInstallationBean.java
public PackageInstallationEntity getInstallationEntity(PackageResolved packageModel, Set<PackageInstallationEntity> requiredDependencies, PackageInstallerHolder packageInstallerHolder) { try {//w ww . ja v a 2 s .c o m // TODO repository version, flavor, etc. CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<PackageInstallationEntity> query = cb.createQuery(PackageInstallationEntity.class); Root<PackageInstallationEntity> p = query.from(PackageInstallationEntity.class); Path<PackageInstallerEntity> pInstaller = p.get(PackageInstallationEntity_.packageInstaller); List<Predicate> predicates = new ArrayList<Predicate>(); predicates.add(cb.equal(p.get(PackageInstallationEntity_.packageName), packageModel.getPackageName())); predicates.add(cb.equal(p.get(PackageInstallationEntity_.sourceVersion).get(Version_.versionNumber), packageModel.getPackageAccessor().getSourceVersion().getVersionNumber())); predicates.add(cb.between(pInstaller.get(PackageInstallerEntity_.version).get(Version_.versionNumber), packageInstallerHolder.getDependencyMinVersion(), packageInstallerHolder.getDependencyMaxVersion())); // TODO flavor arch if (requiredDependencies.isEmpty()) { query.where(cb.and(predicates.toArray(new Predicate[] {}))); } else { SetJoin<PackageInstallationEntity, PackageInstallationEntity> join = p .join(PackageInstallationEntity_.actualDependencies); predicates.add(join.in(requiredDependencies)); // Expression<Set<PackageInstallationEntity>> pDependencies = p // .get(PackageInstallationEntity_.actualDependencies); // predicates.add(pDependencies.in(requiredDependencies)); query.where(cb.and(predicates.toArray(new Predicate[] {}))); Path<Long> pId = p.get(PackageInstallationEntity_.id); query.groupBy(pId); query.having(cb.ge(cb.count(pId), requiredDependencies.size())); query.distinct(true); } return entityManager.createQuery(query).getSingleResult(); } catch (NoResultException e) { return null; } }
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 w w.ja v a 2s . com // 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:ca.uhn.fhir.jpa.dao.SearchBuilder.java
private void addPredicateTag(List<List<? extends IQueryParameterType>> theList, String theParamName, DateRangeParam theLastUpdated) { TagTypeEnum tagType;/*from ww w . j a v a 2s . co m*/ 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.apereo.portal.groups.pags.dao.jpa.JpaPersonAttributesGroupDefinitionDao.java
@Override public void afterPropertiesSet() throws Exception { this.nameParameter = this.createParameterExpression(String.class, "name"); this.findAllDefinitionsQuery = this.createCriteriaQuery( new Function<CriteriaBuilder, CriteriaQuery<PersonAttributesGroupDefinitionImpl>>() { @Override/*from w w w.ja v a2 s . c o m*/ public CriteriaQuery<PersonAttributesGroupDefinitionImpl> apply(CriteriaBuilder cb) { final CriteriaQuery<PersonAttributesGroupDefinitionImpl> criteriaQuery = cb .createQuery(PersonAttributesGroupDefinitionImpl.class); criteriaQuery.from(PersonAttributesGroupDefinitionImpl.class); return criteriaQuery; } }); this.groupDefinitionByNameQuery = this.createCriteriaQuery( new Function<CriteriaBuilder, CriteriaQuery<PersonAttributesGroupDefinitionImpl>>() { @Override public CriteriaQuery<PersonAttributesGroupDefinitionImpl> apply(CriteriaBuilder cb) { final CriteriaQuery<PersonAttributesGroupDefinitionImpl> criteriaQuery = cb .createQuery(PersonAttributesGroupDefinitionImpl.class); Root<PersonAttributesGroupDefinitionImpl> root = criteriaQuery .from(PersonAttributesGroupDefinitionImpl.class); criteriaQuery.select(root).where(cb.equal(root.get("name"), nameParameter)); return criteriaQuery; } }); this.parentGroupDefinitionsQuery = this.createCriteriaQuery( new Function<CriteriaBuilder, CriteriaQuery<PersonAttributesGroupDefinitionImpl>>() { @Override public CriteriaQuery<PersonAttributesGroupDefinitionImpl> apply(CriteriaBuilder cb) { final CriteriaQuery<PersonAttributesGroupDefinitionImpl> criteriaQuery = cb .createQuery(PersonAttributesGroupDefinitionImpl.class); Root<PersonAttributesGroupDefinitionImpl> root = criteriaQuery .from(PersonAttributesGroupDefinitionImpl.class); Join<PersonAttributesGroupDefinitionImpl, PersonAttributesGroupDefinitionImpl> members = root .join(PersonAttributesGroupDefinitionImpl_.members); criteriaQuery.where( cb.equal(members.get(PersonAttributesGroupDefinitionImpl_.name), nameParameter)); return criteriaQuery; } }); }
From source file:org.apereo.portal.persondir.dao.jpa.JpaLocalAccountDaoImpl.java
@Override public List<ILocalAccountPerson> getPeople(LocalAccountQuery query) { final EntityManager entityManager = this.getEntityManager(); final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); final CriteriaQuery<LocalAccountPersonImpl> criteriaQuery = cb.createQuery(LocalAccountPersonImpl.class); final Root<LocalAccountPersonImpl> accountRoot = criteriaQuery.from(LocalAccountPersonImpl.class); final CollectionJoin<LocalAccountPersonImpl, LocalAccountPersonAttributeImpl> attributes = accountRoot .join(LocalAccountPersonImpl_.attributes); final ListJoin<LocalAccountPersonAttributeImpl, String> attributeValues = attributes .join(LocalAccountPersonAttributeImpl_.values); //Due to the joins multiple rows are returned for each result criteriaQuery.distinct(true);//w ww .j a v a2 s.c o m criteriaQuery.select(accountRoot); final List<Predicate> whereParts = new LinkedList<Predicate>(); final Map<Parameter<String>, String> params = new LinkedHashMap<Parameter<String>, String>(); // if a username has been specified, append it to the query if (query.getName() != null) { whereParts.add(cb.equal(accountRoot.get(LocalAccountPersonImpl_.name), this.nameParameter)); params.put(this.nameParameter, query.getName()); } //Build Predicate for each attribute being queried int paramCount = 0; for (Map.Entry<String, List<String>> entry : query.getAttributes().entrySet()) { final List<String> values = entry.getValue(); if (values == null) { continue; } //For each value create a Predicate checking the attribute name and value together for (final String value : values) { if (StringUtils.isBlank(value)) { continue; } //Create Parameter objects for the name and value, stick them in the params map for later use final ParameterExpression<String> nameParam = this.createParameterExpression(String.class, "attrName" + paramCount); final ParameterExpression<String> valueParam = this.createParameterExpression(String.class, "attrValue" + paramCount); params.put(nameParam, entry.getKey()); params.put(valueParam, "%" + value.toLowerCase() + "%"); //Build the and(eq, like) predicate and add it to the list of predicates for the where clause whereParts.add(cb.and(cb.equal(attributes.get(LocalAccountPersonAttributeImpl_.name), nameParam), cb.like(cb.lower(attributeValues.as(String.class)), valueParam))); paramCount++; } } //Add the Predicates to the where clause criteriaQuery.where(cb.or(whereParts.toArray(new Predicate[whereParts.size()]))); //Create the query final TypedQuery<LocalAccountPersonImpl> jpaQuery = this.createCachedQuery(criteriaQuery); //Add all of the stored up parameters to the query for (Map.Entry<Parameter<String>, String> entry : params.entrySet()) { final Parameter<String> parameter = entry.getKey(); final String value = entry.getValue(); jpaQuery.setParameter(parameter, value); } final List<LocalAccountPersonImpl> accounts = jpaQuery.getResultList(); return new ArrayList<ILocalAccountPerson>(accounts); }
From source file:org.batoo.jpa.benchmark.BenchmarkTest.java
private void test(final EntityManagerFactory emf, Queue<Runnable> workQueue, int length) { final CriteriaBuilder cb = emf.getCriteriaBuilder(); final CriteriaQuery<Address> cq = cb.createQuery(Address.class); final Root<Person> r = cq.from(Person.class); final Join<Person, Address> a = r.join("addresses"); a.fetch("country", JoinType.LEFT); a.fetch("person", JoinType.LEFT); cq.select(a);// w ww .j a v a 2 s . c om final ParameterExpression<Person> p = cb.parameter(Person.class); cq.where(cb.equal(r, p)); for (int i = 0; i < length; i++) { workQueue.add(new Runnable() { @Override public void run() { try { BenchmarkTest.this.singleTest(emf, BenchmarkTest.this.createPersons(), cq, p); } catch (final Exception e) { BenchmarkTest.LOG.error(e, "Error while running the test"); } } }); } }
From source file:org.broadleafcommerce.core.catalog.dao.ProductDaoImpl.java
protected List<Product> readFilteredActiveProductsByQueryInternal(String query, Date currentDate, SearchCriteria searchCriteria) { // Set up the criteria query that specifies we want to return Products CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Product> criteria = builder.createQuery(Product.class); // The root of our search is Product since we are searching Root<ProductImpl> product = criteria.from(ProductImpl.class); // We also want to filter on attributes from sku and productAttributes Join<Product, Sku> sku = product.join("defaultSku"); // Product objects are what we want back criteria.select(product);//from w w w.j a v a2 s . c o m // We only want results that match the search query List<Predicate> restrictions = new ArrayList<Predicate>(); String lq = query.toLowerCase(); restrictions.add(builder.or(builder.like(builder.lower(sku.get("name").as(String.class)), '%' + lq + '%'), builder.like(builder.lower(sku.get("longDescription").as(String.class)), '%' + lq + '%'))); attachSearchCriteria(searchCriteria, product, sku, restrictions); attachActiveRestriction(currentDate, product, sku, restrictions); attachOrderBy(searchCriteria, product, sku, criteria); // Execute the query with the restrictions criteria.where(restrictions.toArray(new Predicate[restrictions.size()])); TypedQuery<Product> typedQuery = em.createQuery(criteria); //don't cache - not really practical for open ended search return typedQuery.getResultList(); }
From source file:org.broadleafcommerce.core.catalog.dao.ProductDaoImpl.java
protected List<Product> readFilteredActiveProductsByCategoryInternal(Long categoryId, Date currentDate, SearchCriteria searchCriteria) { // Set up the criteria query that specifies we want to return Products CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Product> criteria = builder.createQuery(Product.class); // The root of our search is Category since we are browsing Root<CategoryProductXrefImpl> productXref = criteria.from(CategoryProductXrefImpl.class); // We want to filter on attributes from product and sku Join<CategoryProductXref, Product> product = productXref.join("product"); Join<Product, Sku> sku = product.join("defaultSku"); Join<CategoryProductXref, Category> category = productXref.join("category"); // Product objects are what we want back criteria.select(product);/* w w w . j ava 2 s .co m*/ // We only want results from the determine category List<Predicate> restrictions = new ArrayList<Predicate>(); restrictions.add(category.get("id").in(sandBoxHelper.mergeCloneIds(CategoryImpl.class, categoryId))); attachSearchCriteria(searchCriteria, product, sku, restrictions); attachActiveRestriction(currentDate, product, sku, restrictions); attachOrderBy(searchCriteria, product, sku, criteria); // Execute the query with the restrictions criteria.where(restrictions.toArray(new Predicate[restrictions.size()])); TypedQuery<Product> typedQuery = em.createQuery(criteria); //don't cache - not really practical for open ended search //typedQuery.setHint(SandBoxHelper.QueryHints.FILTER_INCLUDE, ".*CategoryProductXrefImpl"); return typedQuery.getResultList(); }
From source file:org.broadleafcommerce.core.catalog.dao.ProductDaoImpl.java
protected Long readCountAllActiveProductsInternal(Date currentDate) { // Set up the criteria query that specifies we want to return a Long CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Long> criteria = builder.createQuery(Long.class); // The root of our search is Product Root<ProductImpl> product = criteria.from(ProductImpl.class); // We need to filter on active date on the sku Join<Product, Sku> sku = product.join("defaultSku"); // We want the count of products criteria.select(builder.count(product)); // Ensure the product is currently active List<Predicate> restrictions = new ArrayList<Predicate>(); attachActiveRestriction(currentDate, product, sku, restrictions); // Add the restrictions to the criteria query criteria.where(restrictions.toArray(new Predicate[restrictions.size()])); TypedQuery<Long> query = em.createQuery(criteria); query.setHint(QueryHints.HINT_CACHEABLE, true); query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog"); return query.getSingleResult(); }