Example usage for javax.persistence.criteria Root get

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

Introduction

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

Prototype

<Y> Path<Y> get(SingularAttribute<? super X, Y> attribute);

Source Link

Document

Create a path corresponding to the referenced single-valued attribute.

Usage

From source file:com.netflix.genie.core.jpa.specifications.JpaCommandSpecs.java

/**
 * Get all the clusters given the specified parameters.
 *
 * @param applicationId The id of the application that is registered with these commands
 * @param statuses      The status of the commands
 * @return The specification/*from   w w w . j  a v  a2  s . c  om*/
 */
public static Specification<CommandEntity> findCommandsForApplication(final String applicationId,
        final Set<CommandStatus> statuses) {
    return (final Root<CommandEntity> root, final CriteriaQuery<?> cq, final CriteriaBuilder cb) -> {
        final List<Predicate> predicates = new ArrayList<>();
        final Join<CommandEntity, ApplicationEntity> application = root.join(CommandEntity_.applications);

        predicates.add(cb.equal(application.get(ApplicationEntity_.id), applicationId));

        if (statuses != null && !statuses.isEmpty()) {
            final List<Predicate> orPredicates = statuses.stream()
                    .map(status -> cb.equal(root.get(CommandEntity_.status), status))
                    .collect(Collectors.toList());
            predicates.add(cb.or(orPredicates.toArray(new Predicate[orPredicates.size()])));
        }

        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    };
}

From source file:com.it.j2ee.modules.common.util.DynamicSpecifications.java

public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters,
        final Class<T> entityClazz) {
    return new Specification<T>() {
        public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
            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 = root.get(names[0]);
                    for (int i = 1; i < names.length; i++) {
                        expression = expression.get(names[i]);
                    }/*from   ww  w.j  av  a2 s  .  co m*/

                    // 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:
                        CriteriaBuilder.In in = builder.in(expression);
                        String values = (String) filter.value;
                        String[] value = values.split(",");
                        for (int i = 0; i < value.length; i++) {
                            in.value(value[i]);
                        }
                        predicates.add(in);
                        break;
                    case NEQ:
                        predicates.add(builder.notEqual(expression, (Comparable) filter.value));
                        break;
                    }
                }

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

            return builder.conjunction();
        }
    };
}

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

/**
 * Create a query for fetching a single object
 * /*from  w  w w. j  av a2s .  co  m*/
 * @param entityManager
 *            the entity manager
 * @param entityClass
 *            the entity class
 * @param id
 *            ID of the object to return
 * @param fetchJoins
 *            fetch joins to include
 * @return
 */
public static <ID, T> CriteriaQuery<T> createFetchSingleObjectQuery(EntityManager entityManager,
        Class<T> entityClass, ID id, FetchJoinInformation[] fetchJoins) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<T> cq = builder.createQuery(entityClass);
    Root<T> root = cq.from(entityClass);

    addFetchJoinInformation(root, fetchJoins);

    cq.where(builder.equal(root.get(DynamoConstants.ID), id));
    return cq;
}

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

/**
 * Creates a query that fetches objects based on their IDs
 * //from   www. j  a v  a  2 s  .  co  m
 * @param entityManager
 *            the entity manager
 * @param entityClass
 *            the entity class
 * @param ids
 *            the IDs of the desired entities
 * @param sortOrders
 *            the sorting information
 * @param fetchJoins
 *            the desired fetch joins
 * @return
 */
public static <ID, T> CriteriaQuery<T> createFetchQuery(EntityManager entityManager, Class<T> entityClass,
        List<ID> ids, SortOrders sortOrders, FetchJoinInformation[] fetchJoins) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<T> cq = builder.createQuery(entityClass);
    Root<T> root = cq.from(entityClass);

    boolean distinct = addFetchJoinInformation(root, fetchJoins);

    Expression<String> exp = root.get(DynamoConstants.ID);
    cq.where(exp.in(ids));
    cq.distinct(distinct);

    return addSortInformation(builder, cq, root, sortOrders == null ? null : sortOrders.toArray());
}

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//from   w w w .java  2 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]);
                    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:com.netflix.genie.web.data.repositories.jpa.specifications.JpaClusterSpecs.java

/**
 * Get all the clusters given the specified parameters.
 *
 * @param commandId The id of the command that is registered with this cluster
 * @param statuses  The status of the cluster
 * @return The specification//  w  w w  .  j  a va2s  .co m
 */
public static Specification<ClusterEntity> findClustersForCommand(final String commandId,
        @Nullable final Set<ClusterStatus> statuses) {
    return (final Root<ClusterEntity> root, final CriteriaQuery<?> cq, final CriteriaBuilder cb) -> {
        final List<Predicate> predicates = new ArrayList<>();
        final Join<ClusterEntity, CommandEntity> commands = root.join(ClusterEntity_.commands);

        predicates.add(cb.equal(commands.get(CommandEntity_.uniqueId), commandId));

        if (statuses != null && !statuses.isEmpty()) {
            //Could optimize this as we know size could use native array
            predicates.add(
                    cb.or(statuses.stream().map(status -> cb.equal(root.get(ClusterEntity_.status), status))
                            .toArray(Predicate[]::new)));
        }

        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    };
}

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

/**
 * Creates a query used to retrieve a single entity based on a unique property value
 * /*  w  ww  .j  a  va2s .  c  o m*/
 * @param entityManager
 * @param entityClass
 * @param propertyName
 * @param value
 * @return
 */
public static <T> CriteriaQuery<T> createUniquePropertyQuery(EntityManager entityManager, Class<T> entityClass,
        String propertyName, Object value, boolean caseSensitive) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<T> cq = builder.createQuery(entityClass);
    Root<T> root = cq.from(entityClass);

    Predicate equals = null;
    if (value instanceof String && !caseSensitive) {
        equals = builder.equal(builder.upper(root.get(propertyName).as(String.class)),
                ((String) value).toUpperCase());
    } else {
        equals = builder.equal(root.get(propertyName), value);
    }
    cq.where(equals);

    return cq;
}

From source file:com.netflix.genie.core.jpa.specifications.JpaClusterSpecs.java

/**
 * Get all the clusters given the specified parameters.
 *
 * @param commandId The id of the command that is registered with this cluster
 * @param statuses  The status of the cluster
 * @return The specification/*from w w  w  .j av  a 2  s .co m*/
 */
public static Specification<ClusterEntity> findClustersForCommand(final String commandId,
        final Set<ClusterStatus> statuses) {
    return (final Root<ClusterEntity> root, final CriteriaQuery<?> cq, final CriteriaBuilder cb) -> {
        final List<Predicate> predicates = new ArrayList<>();
        final Join<ClusterEntity, CommandEntity> commands = root.join(ClusterEntity_.commands);

        predicates.add(cb.equal(commands.get(CommandEntity_.id), commandId));

        if (statuses != null && !statuses.isEmpty()) {
            //Could optimize this as we know size could use native array
            final List<Predicate> orPredicates = statuses.stream()
                    .map(status -> cb.equal(root.get(ClusterEntity_.status), status))
                    .collect(Collectors.toList());
            predicates.add(cb.or(orPredicates.toArray(new Predicate[orPredicates.size()])));
        }

        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    };
}

From source file:com.netflix.genie.core.jpa.specifications.JpaJobSpecs.java

/**
 * Generate a criteria query predicate for a where clause based on the given parameters.
 *
 * @param root        The root to use/*  ww w  .  j  av a  2 s .c  om*/
 * @param cb          The criteria builder to use
 * @param id          The job id
 * @param name        The job name
 * @param user        The user who created the job
 * @param statuses    The job statuses
 * @param tags        The tags for the jobs to find
 * @param clusterName The cluster name
 * @param cluster     The cluster the job should have been run on
 * @param commandName The command name
 * @param command     The command the job should have been run with
 * @param minStarted  The time which the job had to start after in order to be return (inclusive)
 * @param maxStarted  The time which the job had to start before in order to be returned (exclusive)
 * @param minFinished The time which the job had to finish after in order to be return (inclusive)
 * @param maxFinished The time which the job had to finish before in order to be returned (exclusive)
 * @return The specification
 */
public static Predicate getFindPredicate(final Root<JobEntity> root, final CriteriaBuilder cb, final String id,
        final String name, final String user, final Set<JobStatus> statuses, final Set<String> tags,
        final String clusterName, final ClusterEntity cluster, final String commandName,
        final CommandEntity command, final Date minStarted, final Date maxStarted, final Date minFinished,
        final Date maxFinished) {
    final List<Predicate> predicates = new ArrayList<>();
    if (StringUtils.isNotBlank(id)) {
        predicates.add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.id), id));
    }
    if (StringUtils.isNotBlank(name)) {
        predicates
                .add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.name), name));
    }
    if (StringUtils.isNotBlank(user)) {
        predicates
                .add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.user), user));
    }
    if (statuses != null && !statuses.isEmpty()) {
        final List<Predicate> orPredicates = statuses.stream()
                .map(status -> cb.equal(root.get(JobEntity_.status), status)).collect(Collectors.toList());
        predicates.add(cb.or(orPredicates.toArray(new Predicate[orPredicates.size()])));
    }
    if (tags != null && !tags.isEmpty()) {
        predicates.add(cb.like(root.get(JobEntity_.tags), JpaSpecificationUtils.getTagLikeString(tags)));
    }
    if (cluster != null) {
        predicates.add(cb.equal(root.get(JobEntity_.cluster), cluster));
    }
    if (StringUtils.isNotBlank(clusterName)) {
        predicates.add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.clusterName),
                clusterName));
    }
    if (command != null) {
        predicates.add(cb.equal(root.get(JobEntity_.command), command));
    }
    if (StringUtils.isNotBlank(commandName)) {
        predicates.add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.commandName),
                commandName));
    }
    if (minStarted != null) {
        predicates.add(cb.greaterThanOrEqualTo(root.get(JobEntity_.started), minStarted));
    }
    if (maxStarted != null) {
        predicates.add(cb.lessThan(root.get(JobEntity_.started), maxStarted));
    }
    if (minFinished != null) {
        predicates.add(cb.greaterThanOrEqualTo(root.get(JobEntity_.finished), minFinished));
    }
    if (maxFinished != null) {
        predicates.add(cb.lessThan(root.get(JobEntity_.finished), maxFinished));
    }
    return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}

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

/**
 * Creates a query to fetch an object based on a value of a unique property
 * /*from  w w w .  ja  v  a 2 s.  c o m*/
 * @param entityManager
 *            the entity manager
 * @param entityClass
 *            the entity class
 * @param fetchJoins
 *            the fetch joins to include
 * @param propertyName
 *            name of the property to search on
 * @param value
 *            value of the property to search on
 * @return
 */
public static <T> CriteriaQuery<T> createUniquePropertyFetchQuery(EntityManager entityManager,
        Class<T> entityClass, FetchJoinInformation[] fetchJoins, String propertyName, Object value,
        boolean caseSensitive) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<T> cq = builder.createQuery(entityClass);
    Root<T> root = cq.from(entityClass);

    addFetchJoinInformation(root, fetchJoins);

    Predicate equals = null;
    if (value instanceof String && !caseSensitive) {
        equals = builder.equal(builder.upper(root.get(propertyName).as(String.class)),
                ((String) value).toUpperCase());
    } else {
        equals = builder.equal(root.get(propertyName), value);
    }
    cq.where(equals);
    cq.distinct(true);

    return cq;
}