Example usage for javax.persistence.criteria CriteriaBuilder and

List of usage examples for javax.persistence.criteria CriteriaBuilder and

Introduction

In this page you can find the example usage for javax.persistence.criteria CriteriaBuilder and.

Prototype

Predicate and(Predicate... restrictions);

Source Link

Document

Create a conjunction of the given restriction predicates.

Usage

From source file:com.orange.clara.tool.controllers.AbstractDefaultController.java

protected List<WatchedResource> getFilteredWatchedResources(User user, boolean isAdmin, String isPublic,
        String tags, String types, Date afterDate) {
    Specification<WatchedResource> specification = new Specification<WatchedResource>() {
        @Override/*from   w  w  w  .j a v a2 s. c  om*/
        public Predicate toPredicate(Root<WatchedResource> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
            List<Predicate> predicates = new ArrayList<>();
            if (tags != null) {
                ListJoin<WatchedResource, Tag> tagJoin = root.joinList("tags");
                predicates.add(cb.isTrue(tagJoin.get("name").in(Tag.namesFromStringList(tags))));
            }
            if (types != null) {
                predicates.add(cb.isTrue(root.get("type").in(ResourceType.fromStringList(types))));
            }
            if (isPublic != null) {
                predicates.add(cb.isTrue(root.get("isPublic")));
            }
            if (afterDate != null) {
                predicates.add(cb.greaterThan(root.get("updatedResourceAt"), afterDate));
            }
            if (!isAdmin) {
                ListJoin<WatchedResource, User> usersJoin = root.joinList("users");
                predicates.add(cb.equal(usersJoin.get("uuid"), user.getUuid()));
            }
            Predicate finalPredicate = cb.and(predicates.toArray(new Predicate[] {}));
            if (isPublic != null) {
                finalPredicate = cb.or(finalPredicate, cb.isTrue(root.get("isPublic")));
            }
            return finalPredicate;
        }
    };
    return this.watchedResourceRepo.findAll(specification);
}

From source file:com.netflix.genie.server.repository.jpa.JobSpecs.java

/**
 * Find jobs based on the parameters.//from   w w  w.  j  ava 2s .co  m
 *
 * @param id          The job id
 * @param jobName     The job name
 * @param userName    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 clusterId   The cluster id
 * @param commandName The command name
 * @param commandId   The command id
 * @return The specification
 */
public static Specification<Job> find(final String id, final String jobName, final String userName,
        final Set<JobStatus> statuses, final Set<String> tags, final String clusterName, final String clusterId,
        final String commandName, final String commandId) {
    return new Specification<Job>() {
        @Override
        public Predicate toPredicate(final Root<Job> root, final CriteriaQuery<?> cq,
                final CriteriaBuilder cb) {
            final List<Predicate> predicates = new ArrayList<>();
            if (StringUtils.isNotBlank(id)) {
                predicates.add(cb.like(root.get(Job_.id), id));
            }
            if (StringUtils.isNotBlank(jobName)) {
                predicates.add(cb.like(root.get(Job_.name), jobName));
            }
            if (StringUtils.isNotBlank(userName)) {
                predicates.add(cb.equal(root.get(Job_.user), userName));
            }
            if (statuses != null && !statuses.isEmpty()) {
                //Could optimize this as we know size could use native array
                final List<Predicate> orPredicates = new ArrayList<>();
                for (final JobStatus status : statuses) {
                    orPredicates.add(cb.equal(root.get(Job_.status), status));
                }
                predicates.add(cb.or(orPredicates.toArray(new Predicate[orPredicates.size()])));
            }
            if (tags != null) {
                for (final String tag : tags) {
                    if (StringUtils.isNotBlank(tag)) {
                        predicates.add(cb.isMember(tag, root.get(Job_.tags)));
                    }
                }
            }
            if (StringUtils.isNotBlank(clusterName)) {
                predicates.add(cb.equal(root.get(Job_.executionClusterName), clusterName));
            }
            if (StringUtils.isNotBlank(clusterId)) {
                predicates.add(cb.equal(root.get(Job_.executionClusterId), clusterId));
            }
            if (StringUtils.isNotBlank(commandName)) {
                predicates.add(cb.equal(root.get(Job_.commandName), commandName));
            }
            if (StringUtils.isNotBlank(commandId)) {
                predicates.add(cb.equal(root.get(Job_.commandId), commandId));
            }
            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        }
    };
}

From source file:com.vladmihalcea.HibernateCriteriaTest.java

private List<Product> getProducts_Mercilessly() {
    return transactionTemplate.execute(new TransactionCallback<List<Product>>() {
        @Override// w w w . j ava 2 s . com
        public List<Product> doInTransaction(TransactionStatus transactionStatus) {
            CriteriaBuilder cb = entityManager.getCriteriaBuilder();
            CriteriaQuery<Product> query = cb.createQuery(Product.class);
            Root<Product> product = query.from(Product.class);
            query.select(product);
            query.distinct(true);

            List<Predicate> criteria = new ArrayList<Predicate>();
            criteria.add(cb.like(cb.lower(product.get(Product_.name)), "%tv%"));

            Subquery<Long> subQuery = query.subquery(Long.class);
            Root<Image> infoRoot = subQuery.from(Image.class);
            Join<Image, Product> productJoin = infoRoot.join(Image_.product);
            subQuery.select(productJoin.<Long>get(Product_.id));

            subQuery.where(cb.gt(infoRoot.get(Image_.index), 0));
            criteria.add(cb.in(product.get(Product_.id)).value(subQuery));
            query.where(cb.and(criteria.toArray(new Predicate[criteria.size()])));
            return entityManager.createQuery(query).getResultList();
        }
    });
}

From source file:com.i5le.framwork.core.persistence.DynamicSpecifications.java

public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters,
        final Class<T> entityClazz) {
    return new Specification<T>() {
        @Override//from  ww  w.j  a va 2s .  co m
        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]);
                    }

                    // 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;

                    }
                }

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

            return builder.conjunction();
        }
    };
}

From source file:com.shz.foundation.service.dynamic.DynamicSpecifications.java

public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters,
        final Class<T> entityClazz) {
    return new Specification<T>() {
        @Override/* w w  w.j  a  va  2 s . c  om*/
        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]);
                    }

                    // logic operator
                    switch (filter.operator) {
                    case EQ:
                        //??
                        Object value = filter.value;
                        if (isBoolean(value)) {
                            value = Boolean.parseBoolean(value.toString());
                        }
                        predicates.add(builder.equal(expression, 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();
        }

        private boolean isBoolean(Object value) {
            String valueString = value.toString().toLowerCase();
            if (valueString.equals("true") || valueString.equals("false"))
                return true;
            return false;
        }
    };
}

From source file:com.frame.base.repository.jpa.DynamicSpecifications.java

public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters,
        final Class<T> entityClazz) {
    return new Specification<T>() {
        @SuppressWarnings({ "rawtypes", "unchecked" })
        @Override/*from ww  w  .  ja  v a 2 s.com*/
        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 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 NE:
                        predicates.add(builder.notEqual(expression, (Comparable) filter.value));
                    case IN:
                        predicates.add(
                                builder.in(expression).in(Arrays.asList(filter.value.toString().split(","))));
                    }
                }

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

            return builder.conjunction();
        }
    };
}

From source file:cc.sion.core.persistence.DynamicSpecifications.java

public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters,
        final Class<T> entityClazz) {
    return new Specification<T>() {
        @Override/*from w  ww.  j  a v  a2  s .c  o  m*/
        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]);
                    }
                    //                  if(log.isDebugEnabled()){
                    //                     log.debug("   {}-{}-{}",names[0],filter.operator,filter.value);
                    //                  }
                    // logic operator
                    switch (filter.operator) {
                    case EQ:
                        predicates.add(builder.equal(expression, filter.value));
                        break;
                    case NE:
                        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();
        }
    };
}

From source file:me.ineson.demo.service.utils.RestUtilsTest.java

@SuppressWarnings("unchecked")
@Test//from ww w  .j  av a  2s.  co  m
public void testParseWhereClauseMultipleWithTransation() {
    CriteriaBuilder criteriaBuilderMock = mock(CriteriaBuilder.class);
    CriteriaQuery<SolarBody> criteriaQueryMock = mock(CriteriaQuery.class);
    Root<SolarBody> rootMock = mock(Root.class);
    log.info("mock root {}, builder {}", rootMock, criteriaBuilderMock);

    Map<String, String> translations = new HashMap<String, String>();
    translations.put("cmrId", "cmr.id");

    Join<Object, Object> nameFieldPath = mock(Join.class, "name field");
    when(rootMock.get("name")).thenReturn(nameFieldPath);

    Join<Object, Object> cmrRecordPath = mock(Join.class, "cmr field");
    when(rootMock.join("cmr")).thenReturn(cmrRecordPath);

    Join<Object, Object> idFieldPath = mock(Join.class, "id field");
    when(cmrRecordPath.get("id")).thenReturn(idFieldPath);

    Predicate firstPredicate = mock(Predicate.class, "1st prediccate");
    when(criteriaBuilderMock.equal(nameFieldPath, "test")).thenReturn(firstPredicate);

    Predicate secondPredicate = mock(Predicate.class, "2nd prediccate");
    when(criteriaBuilderMock.equal(idFieldPath, "22")).thenReturn(secondPredicate);

    Predicate andedPredicates[] = { firstPredicate, secondPredicate };
    Predicate finalPredicate = mock(Predicate.class, "final prediccate");
    when(criteriaBuilderMock.and(andedPredicates)).thenReturn(finalPredicate);

    Predicate predicate = RestUtils.parseWhereClause("name=test,cmrId=22", rootMock, criteriaQueryMock,
            criteriaBuilderMock, translations);

    verify(rootMock, times(1)).get("name");
    verify(rootMock, times(1)).join("cmr");
    verifyNoMoreInteractions(rootMock);

    verify(cmrRecordPath, times(1)).get("id");
    verifyNoMoreInteractions(cmrRecordPath);

    verify(criteriaBuilderMock, times(1)).equal(nameFieldPath, "test");
    verify(criteriaBuilderMock, times(1)).equal(idFieldPath, "22");
    verify(criteriaBuilderMock, times(1)).and(andedPredicates);
    verifyNoMoreInteractions(criteriaBuilderMock);

    Assert.assertEquals(finalPredicate, predicate);
}

From source file:de.hopmann.msc.slave.service.PackageInstallationBean.java

public PackageInstallationEntity getInstallationEntity(PackageResolved packageModel,
        Set<PackageInstallationEntity> requiredDependencies, PackageInstallerHolder packageInstallerHolder) {
    try {/*  ww  w .ja va2  s.co 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: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]);
                    }/* w w w .  j  a  va2 s  .com*/

                    // 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();
        }
    };
}