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

public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters,
        final Class<T> entityClazz) {
    return new Specification<T>() {
        @Override//  ww  w . ja  va 2  s. c  o  m
        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:com.ocs.dynamo.dao.query.JpaQueryBuilder.java

/**
 * Gets property path./*from ww  w. j ava  2 s .co 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:com.netflix.genie.server.repository.jpa.CommandSpecs.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  ww  .ja v  a2 s.  com*/
 */
public static Specification<Command> findCommandsForApplication(final String applicationId,
        final Set<CommandStatus> statuses) {
    return new Specification<Command>() {
        @Override
        public Predicate toPredicate(final Root<Command> root, final CriteriaQuery<?> cq,
                final CriteriaBuilder cb) {
            final List<Predicate> predicates = new ArrayList<>();
            final Join<Command, Application> application = root.join(Command_.application);

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

            if (statuses != null && !statuses.isEmpty()) {
                //Could optimize this as we know size could use native array
                final List<Predicate> orPredicates = new ArrayList<>();
                for (final CommandStatus status : statuses) {
                    orPredicates.add(cb.equal(root.get(Command_.status), status));
                }
                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.server.repository.jpa.ClusterSpecs.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 .  jav  a 2 s .c  o m*/
 */
public static Specification<Cluster> findClustersForCommand(final String commandId,
        final Set<ClusterStatus> statuses) {
    return new Specification<Cluster>() {
        @Override
        public Predicate toPredicate(final Root<Cluster> root, final CriteriaQuery<?> cq,
                final CriteriaBuilder cb) {
            final List<Predicate> predicates = new ArrayList<>();
            final Join<Cluster, Command> commands = root.join(Cluster_.commands);

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

            if (statuses != null && !statuses.isEmpty()) {
                //Could optimize this as we know size could use native array
                final List<Predicate> orPredicates = new ArrayList<>();
                for (final ClusterStatus status : statuses) {
                    orPredicates.add(cb.equal(root.get(Cluster_.status), status));
                }
                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.web.data.repositories.jpa.specifications.JpaJobSpecs.java

/**
 * Generate a criteria query predicate for a where clause based on the given parameters.
 *
 * @param root             The root to use
 * @param cb               The criteria builder to use
 * @param id               The job id//ww  w.j a  v  a 2  s  .c  o  m
 * @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)
 * @param grouping         The job grouping to search for
 * @param groupingInstance The job grouping instance to search for
 * @return The specification
 */
@SuppressWarnings("checkstyle:parameternumber")
public static Predicate getFindPredicate(final Root<JobEntity> root, final CriteriaBuilder cb,
        @Nullable final String id, @Nullable final String name, @Nullable final String user,
        @Nullable final Set<JobStatus> statuses, @Nullable final Set<String> tags,
        @Nullable final String clusterName, @Nullable final ClusterEntity cluster,
        @Nullable final String commandName, @Nullable final CommandEntity command,
        @Nullable final Instant minStarted, @Nullable final Instant maxStarted,
        @Nullable final Instant minFinished, @Nullable final Instant maxFinished,
        @Nullable final String grouping, @Nullable final String groupingInstance) {
    final List<Predicate> predicates = new ArrayList<>();
    if (StringUtils.isNotBlank(id)) {
        predicates.add(
                JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.uniqueId), 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_.tagSearchString), 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));
    }
    if (grouping != null) {
        predicates.add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb, root.get(JobEntity_.grouping),
                grouping));
    }
    if (groupingInstance != null) {
        predicates.add(JpaSpecificationUtils.getStringLikeOrEqualPredicate(cb,
                root.get(JobEntity_.groupingInstance), groupingInstance));
    }
    return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}

From source file:fi.helsinki.opintoni.repository.CommonRepository.java

public <T> List<T> find(Class<T> entityClass, List<Long> ids) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<T> query = criteriaBuilder.createQuery(entityClass);
    Root<T> from = query.from(entityClass);
    query.select(from).where(from.get("id").in(ids));
    return entityManager.createQuery(query).getResultList();
}

From source file:core.commonapp.server.dao.geo.GeoDaoHibernateImpl.java

@Override
public List<Geo> findByGeoType(GeoType type) {
    CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
    CriteriaQuery query = builder.createQuery(Geo.class);

    Root<Geo> root = query.from(Geo.class);
    builder.equal(root.get("geoType"), type);
    return getEntityManager().createQuery(query).getResultList();
}

From source file:net.przemkovv.sphinx.dao.impl.DefaultUserDAO.java

@Override
public User getUser(String email) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<User> cq = cb.createQuery(User.class);
    Root<User> user = cq.from(User.class);
    cq.where(cb.equal(user.get(User_.email), email));
    return em.createQuery(cq).getSingleResult();
}

From source file:net.przemkovv.sphinx.dao.impl.DefaultUserDAO.java

@Override
public boolean existsByEmail(String email) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Long> cq = cb.createQuery(Long.class);
    Root<User> user = cq.from(User.class);
    cq.where(cb.equal(user.get(User_.email), email));
    cq.select(cb.count(user));// w w  w. ja  v  a2s .c  o m
    return em.createQuery(cq).getSingleResult().intValue() == 1;
}

From source file:com.github.lothar.security.acl.jpa.spec.CustomerSpecification.java

@Override
public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
    return cb.equal(root.get("lastName"), lastName);
}