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:eu.domibus.common.dao.MessageLogDao.java

public List<MessageLogEntry> findPaged(int from, int max, String column, boolean asc,
        HashMap<String, Object> filters) {

    CriteriaBuilder cb = this.em.getCriteriaBuilder();
    CriteriaQuery<MessageLogEntry> cq = cb.createQuery(MessageLogEntry.class);
    Root<MessageLogEntry> mle = cq.from(MessageLogEntry.class);
    cq.select(mle);/*from   ww  w  .j  a  v  a2 s.  co m*/
    List<Predicate> predicates = new ArrayList<Predicate>();
    for (Map.Entry<String, Object> filter : filters.entrySet()) {
        if (filter.getValue() != null) {
            if (filter.getValue() instanceof String) {
                if (!filter.getValue().toString().isEmpty()) {
                    switch (filter.getKey().toString()) {
                    case "receivedFrom":
                        predicates.add(cb.greaterThanOrEqualTo(mle.<Date>get("received"),
                                Timestamp.valueOf(filter.getValue().toString())));
                        break;
                    case "receivedTo":
                        predicates.add(cb.lessThanOrEqualTo(mle.<Date>get("received"),
                                Timestamp.valueOf(filter.getValue().toString())));
                        break;
                    default:
                        predicates.add(cb.like(mle.<String>get(filter.getKey()), (String) filter.getValue()));
                        break;
                    }
                }
            } else {
                predicates.add(cb.equal(mle.<String>get(filter.getKey()), filter.getValue()));
            }
        }
    }
    cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
    if (column != null) {
        if (asc) {
            cq.orderBy(cb.asc(mle.get(column)));
        } else {
            cq.orderBy(cb.desc(mle.get(column)));
        }

    }
    final TypedQuery<MessageLogEntry> query = this.em.createQuery(cq);
    query.setFirstResult(from);
    query.setMaxResults(max);
    return query.getResultList();
}

From source file:com.creditcloud.common.entities.dao.AbstractReadDAO.java

/**
 * count entity by ParamInfo// ww  w  . ja v  a2s. c  om
 *
 * @param paramInfo
 * @return
 */
public int count(ParamInfo paramInfo) {
    EntityManager em = getEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery(entityClass);
    Root<T> userRoot = cq.from(entityClass);
    cq.select(cb.count(userRoot));

    //build query for paramInfo
    if (paramInfo != null) {
        Set<Predicate> andCriteria = new HashSet();
        Set<Predicate> orCriteria = new HashSet();

        for (ParamItem item : paramInfo.getParamItems()) {
            Predicate predicate;
            if (item.getValue() instanceof String) {
                //fuzy search for string
                String regExp = "%" + item.getValue() + "%";
                predicate = cb.like((Expression) (userRoot.get(item.getFieldName())), regExp);
            } else {
                predicate = cb.equal((userRoot.get(item.getFieldName())), item.getValue());
            }

            switch (item.getOperator()) {
            case AND:
                andCriteria.add(predicate);
                break;
            case OR:
                orCriteria.add(predicate);
                break;
            }
        }
        if (orCriteria.size() > 0) {
            Predicate or = cb.or(orCriteria.toArray(new Predicate[orCriteria.size()]));
            andCriteria.add(or);
        }
        if (andCriteria.size() > 0) {
            Predicate and = cb.and(andCriteria.toArray(new Predicate[andCriteria.size()]));
            cq.where(and);
        }
    }

    TypedQuery<Long> query = em.createQuery(cq);
    Long result = query.getSingleResult();
    return result == null ? 0 : result.intValue();
}

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/*from w w w  .  ja  v a  2 s  .c o  m*/
 * @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:fi.vm.sade.eperusteet.ylops.service.ops.impl.OpetussuunnitelmaServiceImpl.java

private CriteriaQuery<Opetussuunnitelma> getQuery(OpetussuunnitelmaQuery pquery) {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Opetussuunnitelma> query = builder.createQuery(Opetussuunnitelma.class);
    Root<Opetussuunnitelma> ops = query.from(Opetussuunnitelma.class);

    List<Predicate> ehdot = new ArrayList<>();

    // VAIN JULKAISTUT
    ehdot.add(builder.equal(ops.get(Opetussuunnitelma_.tila), Tila.JULKAISTU));

    // Haettu organisaatio lytyy opsilta
    if (pquery.getOrganisaatio() != null) {
        Expression<Set<String>> organisaatiot = ops.get(Opetussuunnitelma_.organisaatiot);
        ehdot.add(builder.and(builder.isMember(pquery.getOrganisaatio(), organisaatiot)));
    }/*from   www .  ja v  a  2s  .c  om*/

    // Koulutustyyppi
    if (pquery.getKoulutustyyppi() != null) {
        ehdot.add(builder.and(builder.equal(ops.get(Opetussuunnitelma_.koulutustyyppi),
                KoulutusTyyppi.of(pquery.getKoulutustyyppi()))));
    }

    // Perusteen tyyppi
    if (pquery.getTyyppi() != null) {
        ehdot.add(builder.and(builder.equal(ops.get(Opetussuunnitelma_.tyyppi), pquery.getTyyppi())));
    }

    // Perusteen id
    if (pquery.getPerusteenId() != null) {
        Path<PerusteCache> cachedPeruste = ops.join(Opetussuunnitelma_.cachedPeruste);
        ehdot.add(builder
                .and(builder.equal(cachedPeruste.get(PerusteCache_.perusteId), pquery.getPerusteenId())));
    }

    // Perusteen diaarinumero
    if (pquery.getPerusteenDiaarinumero() != null) {
        ehdot.add(builder.and(builder.equal(ops.get(Opetussuunnitelma_.perusteenDiaarinumero),
                pquery.getPerusteenDiaarinumero())));
    }

    query.where(ehdot.toArray(new Predicate[ehdot.size()]));

    return query.select(ops);
}

From source file:com.creditcloud.common.entities.dao.AbstractReadDAO.java

/**
 * list entity by CriteriaInfo/*from  www  . j  ava2s  .co  m*/
 *
 * @param criteriaInfo
 * @return PagedResult
 */
public PagedResult<T> list(CriteriaInfo criteriaInfo) {
    EntityManager em = getEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery(entityClass);
    Root<T> userRoot = cq.from(entityClass);
    cq.select(userRoot);
    ParamInfo paramInfo = criteriaInfo.getParamInfo();
    PageInfo pageInfo = criteriaInfo.getPageInfo();
    SortInfo sortInfo = criteriaInfo.getSortInfo();

    //build query for paramInfo
    if (paramInfo != null) {
        Set<Predicate> andCriteria = new HashSet();
        Set<Predicate> orCriteria = new HashSet();

        for (ParamItem item : paramInfo.getParamItems()) {
            Predicate predicate;
            if (item.getValue() instanceof String) {
                //fuzy search for string
                String regExp = "%" + item.getValue() + "%";
                predicate = cb.like((Expression) (userRoot.get(item.getFieldName())), regExp);
            } else {
                predicate = cb.equal((userRoot.get(item.getFieldName())), item.getValue());
            }

            switch (item.getOperator()) {
            case AND:
                andCriteria.add(predicate);
                break;
            case OR:
                orCriteria.add(predicate);
                break;
            }
        }
        if (orCriteria.size() > 0) {
            Predicate or = cb.or(orCriteria.toArray(new Predicate[orCriteria.size()]));
            andCriteria.add(or);
        }
        if (andCriteria.size() > 0) {
            Predicate and = cb.and(andCriteria.toArray(new Predicate[andCriteria.size()]));
            cq.where(and);
        }
    }

    //build query for sortInfo
    Set<Order> orderPredicate = new HashSet<>();
    if (sortInfo != null) {
        for (SortItem item : sortInfo.getSortItems()) {
            if (item.isDescending()) {
                orderPredicate.add(cb.desc(userRoot.get(item.getFieldName())));
            } else {
                orderPredicate.add(cb.asc(userRoot.get(item.getFieldName())));
            }
        }
    }
    if (orderPredicate.size() > 0) {
        cq.orderBy(orderPredicate.toArray(new Order[orderPredicate.size()]));
    }

    TypedQuery<T> query = em.createQuery(cq);
    //set result range
    if (pageInfo != null) {
        query.setFirstResult(pageInfo.getOffset());
        query.setMaxResults(pageInfo.getSize());
    }

    int totalSize;
    if (paramInfo != null && paramInfo.getParamItems().size() > 0) {
        totalSize = count(paramInfo);
    } else {
        totalSize = count();
    }

    return new PagedResult(query.getResultList(), totalSize);
}

From source file:eu.domibus.common.dao.ErrorLogDao.java

public List<ErrorLogEntry> findPaged(int from, int max, String column, boolean asc,
        HashMap<String, Object> filters) {
    CriteriaBuilder cb = this.em.getCriteriaBuilder();
    CriteriaQuery<ErrorLogEntry> cq = cb.createQuery(ErrorLogEntry.class);
    Root<ErrorLogEntry> ele = cq.from(ErrorLogEntry.class);
    cq.select(ele);/*from w  w w  .jav a  2s .  c  o m*/
    List<Predicate> predicates = new ArrayList<Predicate>();
    for (Map.Entry<String, Object> filter : filters.entrySet()) {
        if (filter.getValue() != null) {
            if (filter.getValue() instanceof String) {
                if (!filter.getValue().toString().isEmpty()) {
                    switch (filter.getKey().toString()) {
                    case "":
                        break;
                    case "timestampFrom":
                        predicates.add(cb.greaterThanOrEqualTo(ele.<Date>get("timestamp"),
                                Timestamp.valueOf(filter.getValue().toString())));
                        break;
                    case "timestampTo":
                        predicates.add(cb.lessThanOrEqualTo(ele.<Date>get("timestamp"),
                                Timestamp.valueOf(filter.getValue().toString())));
                        break;
                    case "notifiedFrom":
                        predicates.add(cb.greaterThanOrEqualTo(ele.<Date>get("notified"),
                                Timestamp.valueOf(filter.getValue().toString())));
                        break;
                    case "notifiedTo":
                        predicates.add(cb.lessThanOrEqualTo(ele.<Date>get("notified"),
                                Timestamp.valueOf(filter.getValue().toString())));
                        break;
                    default:
                        predicates.add(cb.like(ele.<String>get(filter.getKey()), (String) filter.getValue()));
                        break;
                    }
                }
            } else {
                predicates.add(cb.equal(ele.<String>get(filter.getKey()), filter.getValue()));
            }
        }
    }
    cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
    if (column != null) {
        if (asc) {
            cq.orderBy(cb.asc(ele.get(column)));
        } else {
            cq.orderBy(cb.desc(ele.get(column)));
        }

    }
    final TypedQuery<ErrorLogEntry> query = this.em.createQuery(cq);
    query.setFirstResult(from);
    query.setMaxResults(max);
    return query.getResultList();
}

From source file:com.faceye.feature.repository.jpa.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  2s  .  co m*/
        public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
            if (CollectionUtils.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:
                        if (filter.value instanceof Number) {
                            predicates.add(builder.equal(expression, (Number) filter.value));
                        } else if (filter.value instanceof String) {
                            if (StringUtils.isNotEmpty(filter.value.toString())) {
                                predicates.add(builder.equal(expression, filter.value));
                            }
                        } else {
                            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 ISTRUE:
                        predicates.add(builder.isTrue(expression));
                        break;
                    case ISFALSE:
                        predicates.add(builder.isFalse(expression));
                        break;
                    case ISEMPTY:
                        predicates.add(builder.isEmpty(expression));
                        break;
                    case ISNULL:
                        predicates.add(builder.isNull(expression));
                        break;
                    case NE:
                        predicates.add(builder.notEqual(expression, filter.value));
                    }
                }

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

            return builder.conjunction();
        }
    };
}

From source file:com.ims.service.SupportingDataService.java

/**
 * SQL: select * from ims_product_info where CATEGORY_CODE='xxx' and PRODUCT_CODE like '%yyy%' and (CUST_PROD_CODE like '%aaa%' or CUST_PROD_SECOND_CODE like '%aaa%')
 * ??/* ww w .j  a  v  a  2s.c  o  m*/
 *
 * @param prodSearchCriteria
 * @return
 */
public List<ProductInfo> findProductInfoListFrom(final ProdSearchCriteria prodSearchCriteria) {
    Specification<ProductInfo> speci = new Specification<ProductInfo>() {
        @Override
        public Predicate toPredicate(Root<ProductInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            List<Predicate> predicates = new ArrayList<Predicate>();
            Path<String> custProdCode = root.<String>get(ProductInfo.CUST_PROD_CODE);
            Path<String> custProdCode2 = root.<String>get(ProductInfo.CUST_SEC_PROD_CODE);
            Predicate orClause = null;

            if (StringUtils.isNotBlank(prodSearchCriteria.getProdCategoryCode())) {
                predicates.add(cb.equal(root.get(ProductInfo.CATEGORY_CODE),
                        prodSearchCriteria.getProdCategoryCode()));
            }
            if (StringUtils.isNotEmpty(prodSearchCriteria.getProdCode())) {
                predicates.add(cb.like(root.<String>get(ProductInfo.PRODUCT_CODE),
                        getLikeString(prodSearchCriteria.getProdCode())));
            }
            if (StringUtils.isNotBlank(prodSearchCriteria.getCustProdCode())) {
                //??orpredicates?where? query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
                //Predicate p1 = cb.or(cb.like(custProdCode, getLikeString(prodSearchCriteria.getCustProdCode())), cb.like(custProdCode2, getLikeString(prodSearchCriteria.getCustProdCode())));
                //predicates.add(p1);

                //??orPredicate?where????query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])),orClause);
                String param = getLikeString(prodSearchCriteria.getCustProdCode());
                orClause = cb.or(cb.like(custProdCode, param), cb.like(custProdCode2, param));
            }
            //select * from ims_product_info  where CATEGORY_CODE=? and (PRODUCT_CODE like ?) and (CUST_PROD_CODE like ? or CUST_PROD_SECOND_CODE like ?)
            //??
            //query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));

            //??
            if (orClause != null) {
                query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])), orClause);
            } else {
                query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
            }
            return null;
        }
    };

    return productInfoRepository.findAll(speci);
}