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.adeptj.modules.data.jpa.core.AbstractJpaRepository.java

/**
 * {@inheritDoc}/*from   w ww .ja  v a 2  s .c  o m*/
 */
@Override
public <T extends BaseEntity> int deleteByCriteria(DeleteCriteria<T> criteria) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {
        em.getTransaction().begin();
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaDelete<T> cd = cb.createCriteriaDelete(criteria.getEntity());
        Root<T> root = cd.from(criteria.getEntity());
        int rowsDeleted = em
                .createQuery(cd.where(cb.and(Predicates.from(criteria.getCriteriaAttributes(), cb, root))))
                .executeUpdate();
        em.getTransaction().commit();
        LOGGER.debug("deleteByCriteria: No. of rows deleted: [{}]", rowsDeleted);
        return rowsDeleted;
    } catch (Exception ex) { // NOSONAR
        Transactions.markRollback(em);
        throw new JpaException(ex);
    } finally {
        Transactions.rollback(em);
        JpaUtil.closeEntityManager(em);
    }
}

From source file:com.adeptj.modules.data.jpa.core.AbstractJpaRepository.java

/**
 * {@inheritDoc}//w w  w . j a  v  a  2s . c o m
 */
@Override
public <T extends BaseEntity> int updateByCriteria(UpdateCriteria<T> criteria) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {
        em.getTransaction().begin();
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaUpdate<T> cu = cb.createCriteriaUpdate(criteria.getEntity());
        criteria.getUpdateAttributes().forEach(cu::set);
        Root<T> root = cu.from(criteria.getEntity());
        int rowsUpdated = em
                .createQuery(cu.where(cb.and(Predicates.from(criteria.getCriteriaAttributes(), cb, root))))
                .executeUpdate();
        em.getTransaction().commit();
        LOGGER.debug("No. of rows updated: {}", rowsUpdated);
        return rowsUpdated;
    } catch (Exception ex) { // NOSONAR
        Transactions.markRollback(em);
        throw new JpaException(ex);
    } finally {
        Transactions.rollback(em);
        JpaUtil.closeEntityManager(em);
    }
}

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

public List<PurchaseOrder> searchPurchaseOrderList(final OrderSearchCriteria orderSearchCriteria) {
    List<PurchaseOrder> purchaseOrders = new ArrayList<PurchaseOrder>();
    Specification<PurchaseOrder> speci = new Specification<PurchaseOrder>() {
        @Override/*from   w  w  w  .  ja va  2s .com*/
        public Predicate toPredicate(Root<PurchaseOrder> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            List<Predicate> predicates = new ArrayList<Predicate>();
            if (StringUtils.isNotEmpty(orderSearchCriteria.getPurchaseOrderStatus())) {
                predicates.add(cb.equal(root.get("status"), orderSearchCriteria.getPurchaseOrderStatus()));
            }

            if (StringUtils.isNotEmpty(orderSearchCriteria.getPurchaseOrderNum())) {
                predicates.add(cb.like(root.<String>get("purchaseOrderNumber"),
                        "%" + orderSearchCriteria.getPurchaseOrderNum() + "%"));
            }

            if (StringUtils.isNotEmpty(orderSearchCriteria.getProformaInvoiceNum())) {
                predicates.add(cb.like(root.<String>get("piNumber"),
                        "%" + orderSearchCriteria.getProformaInvoiceNum() + "%"));
            }

            query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])))
                    .orderBy(cb.desc(root.get("changeLog").get("createdDate")));
            return null;
        }
    };

    return purchaseOrderRepository.findAll(speci);
}

From source file:name.marcelomorales.siqisiqi.openjpa.impl.OrmFinderImpl.java

protected Predicate newFullTextPredicate(CriteriaBuilder cb, Root<T> p, String terms) {
    LinkedList<Predicate> predicatesOr = Lists.newLinkedList();
    Iterable<Path<String>> fullTexts = settings.getFullTexts(p, persistentClass);
    if (fullTexts != null) {
        for (Path<String> x : fullTexts) {
            StringTokenizer tokenizer = new StringTokenizer(terms, " \t\n\r\f,.;:/");
            LinkedList<Predicate> predicatesAnd = Lists.newLinkedList();
            while (tokenizer.hasMoreTokens()) {
                String token = "%" + tokenizer.nextToken() + "%";

                predicatesAnd.add(cb.like(cb.lower(x), StringUtils.lowerCase(token)));
            }// w  ww .  j av  a  2  s .co  m
            predicatesOr.add(cb.and(predicatesAnd.toArray(new Predicate[predicatesAnd.size()])));
        }
    }
    final Predicate[] restrictions = predicatesOr.toArray(new Predicate[predicatesOr.size()]);
    return cb.or(restrictions);
}

From source file:com.atschx.summer.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  w  w .  j  a v  a 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:
                        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;
                    }
                }

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

            return builder.conjunction();
        }
    };
}

From source file:com.the3.base.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  .j ava 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]);
                    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;
                    }
                }

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

            return builder.conjunction();
        }
    };
}

From source file:org.echoice.modules.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  va2  s. c  o  m*/
        public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
            if (filters != null && filters.size() > 0) {

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

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

            return builder.conjunction();
        }
    };
}

From source file:com.adeptj.modules.data.jpa.core.AbstractJpaRepository.java

/**
 * {@inheritDoc}/*from  w w w . j a  v a  2 s  .  c  o m*/
 */
@Override
public <T extends BaseEntity> List<Tuple> findByTupleQuery(TupleQueryCriteria<T> criteria) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Tuple> cq = cb.createTupleQuery();
        Root<T> root = cq.from(criteria.getEntity());
        return em
                .createQuery(cq
                        .multiselect(criteria.getSelections().stream().map(root::get).toArray(Selection[]::new))
                        .where(cb.and(Predicates.from(criteria.getCriteriaAttributes(), cb, root))))
                .getResultList();
    } catch (Exception ex) { // NOSONAR
        throw new JpaException(ex);
    } finally {
        JpaUtil.closeEntityManager(em);
    }
}

From source file:dtu.ds.warnme.dao.impl.EventsDaoImpl.java

@Override
public List<EventEntity> getNearestEvents(Float nLat, Float sLat, Float eLng, Float wLng,
        EventType... eventTypes) {/*from  w  ww . j a  v a  2 s .  co m*/
    CriteriaBuilder criteriaBuilder = getCriteriaBuilder();
    CriteriaQuery<EventEntity> criteriaQuery = criteriaBuilder.createQuery(EventEntity.class);
    Root<EventEntity> root = criteriaQuery.from(EventEntity.class);

    List<Predicate> predicates = new ArrayList<Predicate>();
    predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get(EventEntity_.latitude), nLat));
    predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get(EventEntity_.latitude), sLat));
    predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get(EventEntity_.longitude), eLng));
    predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get(EventEntity_.longitude), wLng));

    if (ArrayUtils.isNotEmpty(eventTypes)) {
        List<Predicate> eventTypePredicates = new ArrayList<Predicate>();
        for (EventType et : eventTypes) {
            eventTypePredicates.add(criteriaBuilder.equal(root.get(EventEntity_.eventType), et));
        }
        predicates.add(criteriaBuilder.and(
                criteriaBuilder.or(eventTypePredicates.toArray(new Predicate[eventTypePredicates.size()]))));
    }

    criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()]));
    return getAllByCriteria(criteriaQuery);
}

From source file:it.attocchi.jpa2.JPAEntityFilter.java

public CriteriaQuery<T> getCriteria(Class<T> clazz, EntityManagerFactory emf) throws Exception {

    // CriteriaBuilder
    CriteriaBuilder criteriaBuilder = emf.getCriteriaBuilder();

    CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(clazz);
    Root<T> root = criteriaQuery.from(clazz);

    criteriaQuery.select(root);/*from  ww w . j ava  2 s  . c  o  m*/

    // criteria.where( builder.equal( personRoot.get( Utente_.eyeColor ),
    // "brown" ) );

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

    // buildWhere(emf, predicateList, criteriaQuery, criteriaBuilder, root);
    //
    // Predicate[] predicates = new Predicate[predicateList.size()];
    // predicateList.toArray(predicates);

    Predicate[] predicates = getWherePredicates(emf, predicateList, criteriaQuery, criteriaBuilder, root);
    Predicate wherePredicate = criteriaBuilder.and(predicates);
    criteriaQuery.where(wherePredicate);

    // buildSort(criteriaQuery, criteriaBuilder, root);
    List<Order> orders = new ArrayList<Order>();
    buildSort(orders, criteriaQuery, criteriaBuilder, root);
    if (ListUtils.isNotEmpty(orders))
        criteriaQuery.orderBy(orders);

    return criteriaQuery;
}