Example usage for javax.persistence.criteria Path get

List of usage examples for javax.persistence.criteria Path get

Introduction

In this page you can find the example usage for javax.persistence.criteria Path get.

Prototype

<Y> Path<Y> get(String attributeName);

Source Link

Document

Create a path corresponding to the referenced attribute.

Usage

From source file:org.niord.core.area.AreaService.java

/**
 * Searches for areas matching the given search params
 *
 * @param params the sesarch params/* w  ww  . ja va 2 s . com*/
 * @return the search result
 */
@SuppressWarnings("all")
public List<Area> searchAreas(AreaSearchParams params) {

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Area> areaQuery = cb.createQuery(Area.class);

    Root<Area> areaRoot = areaQuery.from(Area.class);

    // Build the predicate
    CriteriaHelper<Area> criteriaHelper = new CriteriaHelper<>(cb, areaQuery);

    // Match the name
    Join<Area, AreaDesc> descs = areaRoot.join("descs", JoinType.LEFT);
    if (params.isExact()) {
        criteriaHelper.equalsIgnoreCase(descs.get("name"), params.getName());
    } else {
        criteriaHelper.like(descs.get("name"), params.getName());
    }

    // Optionally, match the language
    if (StringUtils.isNotBlank(params.getLanguage())) {
        criteriaHelper.equals(descs.get("lang"), params.getLanguage());
    }

    // Optionally, match the parent
    if (params.getParentId() != null) {
        areaRoot.join("parent", JoinType.LEFT);
        Path<Area> parent = areaRoot.get("parent");
        criteriaHelper.equals(parent.get("id"), params.getParentId());
    }

    // Assemple lineage filters from search domain and areas
    Set<String> lineages = new HashSet<>();

    // Optionally, filter by the areas associated with the specified domain
    if (StringUtils.isNotBlank(params.getDomain())) {
        Domain d = domainService.findByDomainId(params.getDomain());
        if (d != null && d.getAreas().size() > 0) {
            d.getAreas().forEach(a -> lineages.add(a.getLineage()));
        }
    }

    // Optionally, filter by area subtrees
    if (params.getAreaIds() != null && !params.getAreaIds().isEmpty()) {
        getAreaDetails(params.getAreaIds()).forEach(a -> lineages.add(a.getLineage()));
    }

    // If defined, apply the area lineage filter
    if (!lineages.isEmpty()) {
        Predicate[] areaMatch = lineages.stream()
                .map(lineage -> cb.like(areaRoot.get("lineage"), lineage + "%")).toArray(Predicate[]::new);
        criteriaHelper.add(cb.or(areaMatch));
    }

    // Optionally, search by type
    if (params.getType() != null) {
        criteriaHelper.add(cb.equal(areaRoot.get("type"), params.getType()));
    }

    // Optionally, require that the area has an associated geometry
    if (params.isGeometry()) {
        criteriaHelper.add(cb.isNotNull(areaRoot.get("geometry")));
    }

    // Optionally, require that the area has an messageSorting type
    if (params.isMessageSorting()) {
        criteriaHelper.add(cb.isNotNull(areaRoot.get("messageSorting")));
    }

    // Unless the "inactive" search flag is set, only include active areas.
    if (!params.isInactive()) {
        criteriaHelper.add(cb.equal(areaRoot.get("active"), true));
    }

    // Compute the sort order
    List<Order> sortOrders = new ArrayList<>();
    if (TREE_SORT_ORDER.equals(params.getSortBy())) {
        Arrays.asList("treeSortOrder", "siblingSortOrder", "id").forEach(field -> {
            if (params.getSortOrder() == PagedSearchParamsVo.SortOrder.ASC) {
                sortOrders.add(cb.asc(areaRoot.get(field)));
            } else {
                sortOrders.add(cb.desc(areaRoot.get(field)));
            }
        });
    }

    // Complete the query
    areaQuery.select(areaRoot).distinct(true).where(criteriaHelper.where()).orderBy(sortOrders);

    // Execute the query and update the search result
    return em.createQuery(areaQuery).setMaxResults(params.getMaxSize()).getResultList();
}

From source file:org.niord.core.category.CategoryService.java

/**
 * Searches for categories matching the given term in the given language
 *
 * @param params the sesarch params/*from w w w .  j  av  a2  s .  c  o m*/
 * @return the search result
 */
@SuppressWarnings("all")
public List<Category> searchCategories(CategorySearchParams params) {

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Category> categoryQuery = cb.createQuery(Category.class);

    Root<Category> categoryRoot = categoryQuery.from(Category.class);

    // Build the predicate
    CriteriaHelper<Category> criteriaHelper = new CriteriaHelper<>(cb, categoryQuery);

    // Match the name
    Join<Category, CategoryDesc> descs = categoryRoot.join("descs", JoinType.LEFT);
    if (params.isExact()) {
        criteriaHelper.equalsIgnoreCase(descs.get("name"), params.getName());
    } else {
        criteriaHelper.like(descs.get("name"), params.getName());
    }

    // Optionally, match the language
    if (StringUtils.isNotBlank(params.getLanguage())) {
        criteriaHelper.equals(descs.get("lang"), params.getLanguage());
    }

    // Optionally, match the parent
    if (params.getParentId() != null) {
        categoryRoot.join("parent", JoinType.LEFT);
        Path<Category> parent = categoryRoot.get("parent");
        criteriaHelper.equals(parent.get("id"), params.getParentId());
    }

    // Optionally, filter by the domains associated with the current domain
    if (StringUtils.isNotBlank(params.getDomain())) {
        Domain d = domainService.findByDomainId(params.getDomain());
        if (d != null && d.getCategories().size() > 0) {
            Predicate[] categoryMatch = d.getCategories().stream()
                    .map(c -> cb.like(categoryRoot.get("lineage"), c.getLineage() + "%"))
                    .toArray(Predicate[]::new);
            criteriaHelper.add(cb.or(categoryMatch));
        }
    }

    // Unless the "inactive" search flag is set, only include active categories.
    if (!params.isInactive()) {
        criteriaHelper.add(cb.equal(categoryRoot.get("active"), true));
    }

    // Complete the query
    categoryQuery.select(categoryRoot).distinct(true).where(criteriaHelper.where());
    //.orderBy(cb.asc(cb.locate(cb.lower(descs.get("name")), name.toLowerCase())));

    // Execute the query and update the search result
    return em.createQuery(categoryQuery).setMaxResults(params.getMaxSize()).getResultList();
}

From source file:org.querybyexample.jpa.ByExampleUtil.java

/**
 * Add a predicate for each simple property whose value is not null.
 *//*from   w w w .  ja  v  a2 s.  c  om*/
public <T> List<Predicate> byExample(ManagedType<T> mt, Path<T> mtPath, T mtValue, SearchParameters sp,
        CriteriaBuilder builder) {
    List<Predicate> predicates = newArrayList();
    for (SingularAttribute<? super T, ?> attr : mt.getSingularAttributes()) {
        if (attr.getPersistentAttributeType() == MANY_TO_ONE //
                || attr.getPersistentAttributeType() == ONE_TO_ONE //
                || attr.getPersistentAttributeType() == EMBEDDED) {
            continue;
        }

        Object attrValue = JpaUtil.getValue(mtValue, attr);
        if (attrValue != null) {
            if (attr.getJavaType() == String.class) {
                if (isNotEmpty((String) attrValue)) {
                    predicates.add(JpaUtil.stringPredicate(mtPath.get(JpaUtil.stringAttribute(mt, attr)),
                            attrValue, sp, builder));
                }
            } else {
                predicates.add(builder.equal(mtPath.get(JpaUtil.attribute(mt, attr)), attrValue));
            }
        }
    }
    return predicates;
}

From source file:org.querybyexample.jpa.ByExampleUtil.java

/**
 * Invoke byExample method for each not null x-to-one association when their pk is not set. This allows you to search entities based on an associated
 * entity's properties value.//w  w  w.jav a  2  s.  c  om
 */
@SuppressWarnings("unchecked")
public <T extends Identifiable<?>, M2O extends Identifiable<?>> List<Predicate> byExampleOnXToOne(
        ManagedType<T> mt, Root<T> mtPath, T mtValue, SearchParameters sp, CriteriaBuilder builder) {
    List<Predicate> predicates = newArrayList();
    for (SingularAttribute<? super T, ?> attr : mt.getSingularAttributes()) {
        if (attr.getPersistentAttributeType() == MANY_TO_ONE
                || attr.getPersistentAttributeType() == ONE_TO_ONE) {
            M2O m2oValue = (M2O) JpaUtil.getValue(mtValue, mt.getAttribute(attr.getName()));
            Class<M2O> m2oType = (Class<M2O>) attr.getBindableJavaType();
            Path<M2O> m2oPath = (Path<M2O>) mtPath.get(attr);
            ManagedType<M2O> m2oMt = em.getMetamodel().entity(m2oType);
            if (m2oValue != null) {
                if (m2oValue.isIdSet()) { // we have an id, let's restrict only on this field
                    predicates.add(builder.equal(m2oPath.get("id"), m2oValue.getId()));
                } else {
                    predicates.addAll(byExample(m2oMt, m2oPath, m2oValue, sp, builder));
                }
            }
        }
    }
    return predicates;
}

From source file:org.sparkcommerce.core.catalog.dao.ProductDaoImpl.java

protected void attachOrderBy(ProductSearchCriteria searchCriteria, From<?, ? extends Product> product,
        Path<? extends Sku> sku, CriteriaQuery<?> criteria) {
    if (StringUtils.isNotBlank(searchCriteria.getSortQuery())) {
        CriteriaBuilder builder = em.getCriteriaBuilder();

        List<Order> sorts = new ArrayList<Order>();

        String sortQueries = searchCriteria.getSortQuery();
        for (String sortQuery : sortQueries.split(",")) {
            String[] sort = sortQuery.split(" ");
            if (sort.length == 2) {
                String key = sort[0];
                boolean asc = sort[1].toLowerCase().contains("asc");

                // Determine whether we should use the product path or the sku path
                Path<?> pathToUse;
                if (key.contains("defaultSku.")) {
                    pathToUse = sku;/*from w w w  .  j  a  v a  2  s  .c o m*/
                    key = key.substring("defaultSku.".length());
                } else if (key.contains("product.")) {
                    pathToUse = product;
                    key = key.substring("product.".length());
                } else {
                    // We don't know which path this facet is built on - resolves previous bug that attempted
                    // to attach search facet to any query parameter
                    continue;
                }

                if (asc) {
                    sorts.add(builder.asc(pathToUse.get(key)));
                } else {
                    sorts.add(builder.desc(pathToUse.get(key)));
                }
            }
        }

        criteria.orderBy(sorts.toArray(new Order[sorts.size()]));
    }
}

From source file:org.sparkcommerce.core.catalog.dao.ProductDaoImpl.java

protected void attachProductSearchCriteria(ProductSearchCriteria searchCriteria,
        From<?, ? extends Product> product, From<?, ? extends Sku> sku, List<Predicate> restrictions) {
    CriteriaBuilder builder = em.getCriteriaBuilder();

    // Build out the filter criteria from the users request
    for (Entry<String, String[]> entry : searchCriteria.getFilterCriteria().entrySet()) {
        String key = entry.getKey();
        List<String> eqValues = new ArrayList<String>();
        List<String[]> rangeValues = new ArrayList<String[]>();

        // Determine which path is the appropriate one to use
        Path<?> pathToUse;
        if (key.contains("defaultSku.")) {
            pathToUse = sku;/*from   w w  w .  j a  va2s  . c  om*/
            key = key.substring("defaultSku.".length());
        } else if (key.contains("productAttributes.")) {
            pathToUse = product.join("productAttributes");

            key = key.substring("productAttributes.".length());
            restrictions.add(builder.equal(pathToUse.get("name").as(String.class), key));

            key = "value";
        } else if (key.contains("product.")) {
            pathToUse = product;
            key = key.substring("product.".length());
        } else {
            // We don't know which path this facet is built on - resolves previous bug that attempted
            // to attach search facet to any query parameter
            continue;
        }

        // Values can be equality checks (ie manufacturer=Dave's) or range checks, which take the form
        // key=range[minRange:maxRange]. Figure out what type of check this is
        for (String value : entry.getValue()) {
            if (value.contains("range[")) {
                String[] rangeValue = new String[] {
                        value.substring(value.indexOf("[") + 1, value.indexOf(":")),
                        value.substring(value.indexOf(":") + 1, value.indexOf("]")) };
                rangeValues.add(rangeValue);
            } else {
                eqValues.add(value);
            }
        }

        // Add the equality range restriction with the "in" builder. That means that the query string
        // ?manufacturer=Dave&manufacturer=Bob would match either Dave or Bob
        if (eqValues.size() > 0) {
            restrictions.add(pathToUse.get(key).in(eqValues));
        }

        // If we have any range restrictions, we need to build those too. Ranges are also "or"ed together,
        // such that specifying range[0:5] and range[10:null] for the same field would match items
        // that were valued between 0 and 5 OR over 10 for that field
        List<Predicate> rangeRestrictions = new ArrayList<Predicate>();
        for (String[] range : rangeValues) {
            BigDecimal min = new BigDecimal(range[0]);
            BigDecimal max = null;
            if (range[1] != null && !range[1].equals("null")) {
                max = new BigDecimal(range[1]);
            }

            Predicate minRange = builder.greaterThan(pathToUse.get(key).as(BigDecimal.class), min);
            Predicate maxRange = null;
            if (max != null) {
                maxRange = builder.lessThan(pathToUse.get(key).as(BigDecimal.class), max);
                rangeRestrictions.add(builder.and(minRange, maxRange));
            } else {
                rangeRestrictions.add(minRange);
            }
        }

        if (rangeRestrictions.size() > 0) {
            restrictions.add(builder.or(rangeRestrictions.toArray(new Predicate[rangeRestrictions.size()])));
        }
    }
}

From source file:org.vaadin.addons.javaee.container.jpa.filter.EqualFilterTranslator.java

@SuppressWarnings("unchecked")
protected <ENTITY extends PersistentEntity> Path<String> navigateThroughPath(Root<ENTITY> root,
        String propertyId) {//  w w w. j a  v a2s.c  o m
    Path<?> path = root;
    for (String pathElement : StringUtils.split(propertyId, ".")) {
        path = path.get(pathElement);
    }
    return (Path<String>) path;
}

From source file:org.xiaoqiaotq.util.persistence.DynamicSpecifications.java

public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters,
        final Class<T> entityClazz) {
    return new Specification<T>() {
        @Override/*  w  ww  . j a  v a2  s .  c om*/
        public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
            if ((filters != null) && !(filters.isEmpty())) {

                List<Predicate> predicates = Lists.newArrayList();
                for (SearchFilter filter : filters) {
                    // nested path translate, Task??"user.name"filedName, ?Task.user.name
                    String[] names = StringUtils.split(filter.fieldName, ".");
                    Path expression = root.get(names[0]);
                    for (int i = 1; i < names.length; i++) {
                        expression = expression.get(names[i]);
                    }
                    // logic operator
                    switch (filter.operator) {
                    case EQ:
                        predicates.add(builder.equal(expression, filter.value));
                        break;
                    case NEQ:
                        predicates.add(builder.notEqual(expression, filter.value));
                        break;
                    case LIKE:
                        predicates.add(builder.like(expression, "%" + filter.value + "%"));
                        break;
                    case GT:
                        predicates.add(builder.greaterThan(expression, (Comparable) filter.value));
                        break;
                    case LT:
                        predicates.add(builder.lessThan(expression, (Comparable) filter.value));
                        break;
                    case GTE:
                        predicates.add(builder.greaterThanOrEqualTo(expression, (Comparable) filter.value));
                        break;
                    case LTE:
                        predicates.add(builder.lessThanOrEqualTo(expression, (Comparable) filter.value));
                        break;
                    }
                }

                // ? and ???
                if (!predicates.isEmpty()) {
                    return builder.and(predicates.toArray(new Predicate[predicates.size()]));
                }
            }

            return builder.conjunction();
        }
    };
}