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:aode.lx.persistence.DynamicSpecifications.java

public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters,
        final Class<T> entityClazz) {
    return new Specification<T>() {
        @Override//from w  w  w.  j a v  a  2 s .  com
        public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
            if (Collections3.isNotEmpty(filters)) {

                List<Predicate> predicates = Lists.newArrayList();
                List<Predicate> ORpredicates = 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]);
                    }

                    Object value = filter.value;

                    if (expression.getJavaType().isEnum()) {
                        value = EnumUtils.valueOf(expression.getJavaType(), filter.value.toString());
                        predicates.add(builder.equal(expression, value));
                    } else {
                        // logic operator
                        switch (filter.operator) {
                        case EQ:
                            predicates.add(builder.equal(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;
                        case NEQ:
                            predicates.add(builder.notEqual(expression, filter.value));
                            break;
                        case NOTNULL:
                            predicates.add(builder.isNotNull(expression));
                            break;
                        case ISNULL:
                            predicates.add(builder.isNull(expression));
                            break;
                        case OREQ:
                            ORpredicates.add(builder.equal(expression, filter.value));
                            break;
                        case ORLIKE:
                            ORpredicates.add(builder.like(expression, "%" + filter.value + "%"));
                            break;
                        case ORGT:
                            ORpredicates.add(builder.greaterThan(expression, (Comparable) filter.value));
                            break;
                        case ORLT:
                            ORpredicates.add(builder.lessThan(expression, (Comparable) filter.value));
                            break;
                        case ORGTE:
                            ORpredicates
                                    .add(builder.greaterThanOrEqualTo(expression, (Comparable) filter.value));
                            break;
                        case ORLTE:
                            ORpredicates.add(builder.lessThanOrEqualTo(expression, (Comparable) filter.value));
                            break;
                        case ORNEQ:
                            ORpredicates.add(builder.notEqual(expression, filter.value));
                            break;
                        case ORNOTNULL:
                            ORpredicates.add(builder.isNotNull(expression));
                            break;
                        case ORISNULL:
                            ORpredicates.add(builder.isNull(expression));
                            break;
                        }
                    }

                }

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

From source file:cn.imethan.common.repository.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  a 2s. 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]);
                    try {
                        for (int i = 1; i < names.length; i++) {
                            expression = expression.get(names[i]);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    // logic operator
                    switch (filter.operator) {
                    case EQ:
                        predicates.add(builder.equal(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;
                    case IN:
                        In in = builder.in(expression);
                        String[] valueStrings = StringUtils.split(filter.value.toString(), ",");
                        List<Long> list = new ArrayList<Long>();
                        for (String value : valueStrings) {
                            list.add(Long.valueOf(value.trim()));
                        }
                        in.value(list);

                        predicates.add(in);

                        break;
                    case NOTIN:
                        In in1 = builder.in(expression);
                        String[] valueStrings1 = StringUtils.split(filter.value.toString(), ",");
                        List<Long> list1 = new ArrayList<Long>();
                        for (String value : valueStrings1) {
                            list1.add(Long.valueOf(value.trim()));
                        }
                        in1.value(list1);

                        predicates.add(builder.not(in1));
                        break;
                    }
                }

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

            //            //hibernate
            //            //org.hibernate.ejb.criteria.CriteriaQueryImpl
            //            if(query instanceof org.hibernate.ejb.QueryImpl) {  
            //               @SuppressWarnings("rawtypes")
            //               org.hibernate.ejb.QueryImpl hibernateQuery = (org.hibernate.ejb.QueryImpl)query;  
            //               org.hibernate.Query hQuery = hibernateQuery.getHibernateQuery();
            //               hQuery.setCacheable(true);
            //            }

            return builder.conjunction();
        }
    };
}

From source file:net.sf.companymanager.qbe.JpaUtil.java

/**
 * Convert the passed propertyPath into a JPA path. Note: JPA will do joins
 * if the property is in an associated/*from   w w  w  .  ja  va2  s  .co  m*/
 * entity.
 */
private static <E> Path<?> getPropertyPath(final Path<E> root, final String propertyPath) {
    String[] pathItems = StringUtils.split(propertyPath, ".");

    Path<?> path = root.get(pathItems[0]);
    for (int i = 1; i < pathItems.length; i++) {
        path = path.get(pathItems[i]);
    }
    return path;
}

From source file:com.github.dactiv.orm.core.spring.data.jpa.specification.Specifications.java

/**
 * ???//from www .  ja v a  2 s . com
 * 
 * @param propertyName ??
 * @param root Query roots always reference entities
 * 
 * @return {@link Path}
 */
public static Path<?> getPath(String propertyName, Root<?> root) {

    Path<?> path = null;

    if (StringUtils.contains(propertyName, ".")) {
        String[] propertys = StringUtils.splitByWholeSeparator(propertyName, ".");
        path = root.get(propertys[0]);
        for (int i = 1; i < propertys.length; i++) {
            path = path.get(propertys[i]);
        }
    } else {
        path = root.get(propertyName);
    }

    return path;
}

From source file:org.pushio.webapp.support.persistence.DynamicSpecifications.java

/**
 * @see ??JPA/*ww w  . j  a  v  a  2s.co m*/
 * @param filters
 * @param entityClazz
 * @param isDistinct  trueSQLdistinctfalse?
 * @return
 */
public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters,
        final Class<T> entityClazz, final boolean isDistinct, final List<OrderParam> orderParams) {
    return new Specification<T>() {
        @Override
        public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
            if (orderParams != null && orderParams.size() > 0) {
                /*
                CriteriaQuery<Foo> criteriaQuery = criteriaBuilder.createQuery(Foo.class);
                Root<Foo> from = criteriaQuery.from(Foo.class);
                CriteriaQuery<Foo> select = criteriaQuery.select(from);
                criteriaQuery.orderBy(criteriaBuilder.asc(from.get("name")));
                */
                List<Order> orders = new ArrayList<Order>(orderParams.size());
                for (OrderParam orderParam : orderParams) {
                    if (orderParam != null && orderParam.getField() != null) {
                        String fields[] = StringUtil.split(orderParam.getField(), '.');
                        Path expression = (fields.length > 1) ? root.join(fields[0]) : root.get(fields[0]);
                        for (int i = 1, len = fields.length; i < len; ++i) {
                            expression = expression.get(fields[i]);
                        }
                        if (expression != null) {
                            Order order = (orderParam.getType() == null
                                    || orderParam.getType().equalsIgnoreCase("asc")) ? builder.asc(expression)
                                            : builder.desc(expression);
                            orders.add(order);
                            //                        query.orderBy(order);
                        }
                    }
                }
                query.orderBy(orders);
            }
            query.distinct(isDistinct);
            if (Collections3.isNotEmpty(filters)) {
                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 = null;

                    //////  ?
                    boolean hasJoin = names[0].startsWith("[join]");
                    String fn = hasJoin ? names[0].substring(6) : names[0];
                    boolean isNotDateType = !(filter.value instanceof Date);
                    try {
                        expression = hasJoin ? root.join(fn) : root.get(fn);
                        if (isNotDateType && isDateType(expression.getJavaType())) {
                            // filter.value??
                            filter.value = parseDate(filter.value.toString(), filter.operator);
                        }
                    } catch (Exception e) {
                        //                     logger.error(e.getMessage(), e);
                        continue; // ??
                    }
                    boolean isPropertyNotValid = false;
                    for (int i = 1; i < names.length; i++) {
                        try {
                            expression = expression.get(names[i]);
                            if (isNotDateType && isDateType(expression.getJavaType())) {
                                filter.value = parseDate(filter.value.toString(), filter.operator);
                            }
                        } catch (Exception e) {
                            //                        logger.error(e.getMessage(), e);
                            isPropertyNotValid = true; // 
                            break; // ??
                        }
                    }
                    if (expression == null || isPropertyNotValid) {
                        continue;
                    }
                    ///////

                    // logic operator
                    switch (filter.operator) {
                    case EQ:
                        predicates.add(builder.equal(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;
                    case ORLIKE:
                        if (filter.value instanceof String) {
                            String value = (String) filter.value;
                            String[] values = value.split(",");
                            Predicate[] like = new Predicate[values.length];
                            for (int i = 0; i < values.length; i++) {
                                like[i] = builder.like(expression, "%" + values[i] + "%");
                            }
                            predicates.add(builder.or(like));
                        }

                        break;
                    case ANDLIKE:
                        if (filter.value instanceof String) {
                            String value = (String) filter.value;
                            String[] values = value.split(",");
                            Predicate[] like = new Predicate[values.length];
                            for (int i = 0; i < values.length; i++) {
                                like[i] = builder.like(expression, "%" + values[i] + "%");
                            }
                            predicates.add(builder.and(like));
                        }
                        break;
                    case ANDNOTLIKE:
                        if (filter.value instanceof String) {
                            String value = (String) filter.value;
                            String[] values = value.split(",");
                            Predicate[] like = new Predicate[values.length];
                            for (int i = 0; i < values.length; i++) {
                                like[i] = builder.notLike(expression, "%" + values[i] + "%");
                            }
                            predicates.add(builder.and(like));
                        }
                        break;
                    case OREQ:
                        if (filter.value instanceof String) {
                            String value = (String) filter.value;
                            String[] values = value.split(",");
                            Predicate[] like = new Predicate[values.length];
                            for (int i = 0; i < values.length; i++) {
                                like[i] = builder.equal(expression, values[i]);
                            }
                            predicates.add(builder.or(like));
                        }
                        break;

                    case ANDNOTEQ:
                        if (filter.value instanceof String) {
                            String value = (String) filter.value;
                            String[] values = value.split(",");
                            Predicate[] like = new Predicate[values.length];
                            for (int i = 0; i < values.length; i++) {
                                like[i] = builder.notEqual(expression, values[i]);
                            }
                            predicates.add(builder.and(like));
                        }
                        break;
                    case NOTEQ:
                        predicates.add(builder.notEqual(expression, (Comparable) filter.value));
                        break;
                    case NOTLIKE:
                        predicates.add(builder.notLike(expression, "%" + filter.value + "%"));
                        break;
                    case NULL:
                        predicates.add(builder.isNull(expression));
                        break;
                    case NOTNULL:
                        predicates.add(builder.isNotNull(expression));
                        break;
                    //                  case IN:
                    //                     predicates.add(builder.in(expression).in(values));
                    //                     break;
                    }
                }

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

            return builder.conjunction();
        }
    };
}

From source file:br.nom.abdon.gastoso.dal.FatosDao.java

protected static void buildQuery(final CriteriaBuilder cb, final FiltroFatos filtroFatos,
        final Path<Fato> fatoPath, final List<Predicate> where, final Map<String, Object> params) {

    final Fato fato = filtroFatos.getFato();
    if (fato != null) {
        final ParameterExpression<Fato> fatoParameter = cb.parameter(Fato.class, "fato");

        where.add(cb.equal(fatoParameter, fatoPath));
        params.put("fato", fato);

    }/*from www . j a  v a 2  s  .  c om*/

    final LocalDate dataMaxima = filtroFatos.getDataMaxima();
    if (dataMaxima != null) {
        final Path<LocalDate> diaPath = fatoPath.get("dia");

        final ParameterExpression<LocalDate> dataMaximaParameter = cb.parameter(LocalDate.class, "dataMaxima");

        final Predicate menorOuIgualDataMaxima = cb.lessThanOrEqualTo(diaPath, dataMaximaParameter);

        where.add(menorOuIgualDataMaxima);
        params.put("dataMaxima", dataMaxima);
    }

    final LocalDate dataMinima = filtroFatos.getDataMinima();
    if (dataMinima != null) {
        final Path<LocalDate> diaPath = fatoPath.get("dia");

        final ParameterExpression<LocalDate> dataMinimaParameter = cb.parameter(LocalDate.class, "dataMinima");

        final Predicate maiorOuIgualQueDataMinima = cb.greaterThanOrEqualTo(diaPath, dataMinimaParameter);

        where.add(maiorOuIgualQueDataMinima);
        params.put("dataMinima", dataMinima);
    }
}

From source file:org.jdal.dao.jpa.JpaUtils.java

/**
 * Gets a Path from Path using property path
 * @param path the base path/*from   w w  w. ja  v a2s  .c o  m*/
 * @param propertyPath property path String like "customer.order.price"
 * @return a new Path for property
 */
@SuppressWarnings("unchecked")
public static <T> Path<T> getPath(Path<?> path, String propertyPath) {
    if (StringUtils.isEmpty(propertyPath))
        return (Path<T>) path;

    String name = StringUtils.substringBefore(propertyPath, PropertyUtils.PROPERTY_SEPARATOR);
    Path<?> p = path.get(name);

    return getPath(p, StringUtils.substringAfter(propertyPath, PropertyUtils.PROPERTY_SEPARATOR));

}

From source file:com.ocs.dynamo.dao.query.JpaQueryBuilder.java

/**
 * Gets property path.//from   ww w. j  ava2  s  . c  o  m
 * 
 * @param root
 *            the root where path starts form
 * @param propertyId
 *            the property ID
 * @return the path to property
 */
private static Path<Object> getPropertyPath(Root<?> root, Object propertyId) {
    String[] propertyIdParts = ((String) propertyId).split("\\.");

    Path<Object> path = null;
    for (String part : propertyIdParts) {
        if (path == null) {
            path = root.get(part);
        } else {
            path = path.get(part);
        }
    }
    return path;
}

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

/**
 * Convert the passed propertyPath into a JPA path.
 * <p>// www .j a  va  2  s. c  o  m
 * Note: JPA will do joins if the property is in an associated entity.
 */
@SuppressWarnings("unchecked")
public static <E, F> Path<F> getPath(Root<E> root, List<Attribute<?, ?>> attributes) {
    Path<?> path = root;
    for (Attribute<?, ?> attribute : attributes) {
        boolean found = false;
        // handle case when order on already fetched attribute
        for (Fetch<E, ?> fetch : root.getFetches()) {
            if (attribute.getName().equals(fetch.getAttribute().getName()) && (fetch instanceof Join<?, ?>)) {
                path = (Join<E, ?>) fetch;
                found = true;
                break;
            }
        }
        for (Join<E, ?> join : root.getJoins()) {
            if (attribute.getName().equals(join.getAttribute().getName())) {
                path = join;
                found = true;
                break;
            }
        }
        if (!found) {
            path = path.get(attribute.getName());
        }
    }
    return (Path<F>) path;
}

From source file:org.oncoblocks.centromere.jpa.test.EntrezGeneRepositoryImpl.java

public List<EntrezGene> guessGene(String keyword) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<EntrezGene> query = builder.createQuery(EntrezGene.class);
    Root<EntrezGene> root = query.from(EntrezGene.class);
    query.where(builder.equal(root.get("primaryGeneSymbol"), keyword));
    List<EntrezGene> genes = entityManager.createQuery(query).getResultList();
    if (genes != null && genes.size() > 0)
        return genes;

    query = builder.createQuery(EntrezGene.class);
    root = query.from(EntrezGene.class);
    Path join = root.join("aliases");
    query.where(builder.equal(join.get("name"), keyword));
    return entityManager.createQuery(query).getResultList();
}