Example usage for javax.persistence.criteria CriteriaQuery where

List of usage examples for javax.persistence.criteria CriteriaQuery where

Introduction

In this page you can find the example usage for javax.persistence.criteria CriteriaQuery where.

Prototype

CriteriaQuery<T> where(Predicate... restrictions);

Source Link

Document

Modify the query to restrict the query result according to the conjunction of the specified restriction predicates.

Usage

From source file:org.apache.wookie.beans.jpa.JPAPersistenceManager.java

@SuppressWarnings("unchecked")
public <T extends IBean> T[] findByValue(Class<T> beansInterface, String name, Object value, String orderBy,
        boolean ascending) {
    // validate entity manager transaction
    if (entityManager == null) {
        throw new IllegalStateException("Transaction not initiated or already closed");
    }// w w  w.  j  a  v a 2 s  .c o m

    // validate bean interface
    Class<? extends IBean> beanClass = BEAN_INTERFACE_TO_CLASS_MAP.get(beansInterface);
    if (beanClass == null) {
        throw new IllegalArgumentException("Invalid bean interface specified");
    }

    // get persistent beans by criteria
    try {
        // construct query criteria
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<? extends IBean> criteriaQuery = criteriaBuilder.createQuery(beanClass);
        Root<? extends IBean> beanRoot = criteriaQuery.from(beanClass);
        if (name != null) {
            criteriaQuery.where((value != null) ? criteriaBuilder.equal(beanRoot.get(name), value)
                    : criteriaBuilder.isNull(beanRoot.get(name)));
        }
        if (orderBy != null) {
            criteriaQuery.orderBy(ascending ? criteriaBuilder.asc(beanRoot.get(orderBy))
                    : criteriaBuilder.desc(beanRoot.get(orderBy)));
        }

        // invoke query
        Query query = entityManager.createQuery(criteriaQuery);
        List<? extends IBean> beansList = query.getResultList();
        if ((beansList != null) && !beansList.isEmpty()) {
            return beansList.toArray((T[]) Array.newInstance(beansInterface, beansList.size()));
        }
    } catch (Exception e) {
        logger.error("Unexpected exception: " + e, e);
    }
    return (T[]) Array.newInstance(beansInterface, 0);
}

From source file:org.broadleafcommerce.core.catalog.dao.ProductDaoImpl.java

protected Long readCountAllActiveProductsInternal(Date currentDate) {
    // Set up the criteria query that specifies we want to return a Long
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Long> criteria = builder.createQuery(Long.class);

    // The root of our search is Product
    Root<ProductImpl> product = criteria.from(ProductImpl.class);

    // We need to filter on active date on the sku
    Join<Product, Sku> sku = product.join("defaultSku");

    // We want the count of products
    criteria.select(builder.count(product));

    // Ensure the product is currently active
    List<Predicate> restrictions = new ArrayList<Predicate>();
    attachActiveRestriction(currentDate, product, sku, restrictions);

    // Add the restrictions to the criteria query
    criteria.where(restrictions.toArray(new Predicate[restrictions.size()]));

    TypedQuery<Long> query = em.createQuery(criteria);
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    query.setHint(QueryHints.HINT_CACHE_REGION, "query.Catalog");

    return query.getSingleResult();
}

From source file:org.openlmis.migration.tool.openlmis.referencedata.repository.custom.impl.OlmisFacilityTypeApprovedProductRepositoryImpl.java

@Override
public Collection<FacilityTypeApprovedProduct> searchProducts(UUID facilityId, UUID programId,
        boolean fullSupply) {
    checkNotNull(facilityId);//www.j  a v a2  s .  c o  m

    CriteriaBuilder builder = entityManager.getCriteriaBuilder();

    CriteriaQuery<FacilityTypeApprovedProduct> query = builder.createQuery(FacilityTypeApprovedProduct.class);

    Root<FacilityTypeApprovedProduct> ftap = query.from(FacilityTypeApprovedProduct.class);
    Root<Facility> facility = query.from(Facility.class);

    Join<Facility, FacilityType> fft = facility.join("type");

    Join<FacilityTypeApprovedProduct, FacilityType> ft = ftap.join("facilityType");
    Join<FacilityTypeApprovedProduct, ProgramOrderable> pp = ftap.join("programOrderable");

    Join<ProgramOrderable, Program> program = pp.join("program");

    Predicate conjunction = builder.conjunction();
    if (programId != null) {
        conjunction = builder.and(conjunction, builder.equal(program.get("id"), programId));
    }
    conjunction = builder.and(conjunction, builder.equal(fft.get("id"), ft.get("id")));
    conjunction = builder.and(conjunction, builder.equal(facility.get("id"), facilityId));
    conjunction = builder.and(conjunction, builder.equal(pp.get("fullSupply"), fullSupply));
    conjunction = builder.and(conjunction, builder.isTrue(pp.get("active")));

    query.select(ftap);
    query.where(conjunction);

    Join<ProgramOrderable, OrderableDisplayCategory> category = pp.join("orderableDisplayCategory");
    Join<ProgramOrderable, Orderable> orderable = pp.join("product");

    query.orderBy(builder.asc(category.get("orderedDisplayValue").get("displayOrder")),
            builder.asc(category.get("orderedDisplayValue").get("displayName")),
            builder.asc(orderable.get("productCode")));

    return entityManager.createQuery(query).getResultList();
}

From source file:net.groupbuy.dao.impl.BaseDaoImpl.java

protected Long count(CriteriaQuery<T> criteriaQuery, List<Filter> filters) {
    Assert.notNull(criteriaQuery);/*from   w  w w  . j a  v a 2s . co m*/
    Assert.notNull(criteriaQuery.getSelection());
    Assert.notEmpty(criteriaQuery.getRoots());

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    addRestrictions(criteriaQuery, filters);

    CriteriaQuery<Long> countCriteriaQuery = criteriaBuilder.createQuery(Long.class);
    for (Root<?> root : criteriaQuery.getRoots()) {
        Root<?> dest = countCriteriaQuery.from(root.getJavaType());
        dest.alias(getAlias(root));
        copyJoins(root, dest);
    }

    Root<?> countRoot = getRoot(countCriteriaQuery, criteriaQuery.getResultType());
    countCriteriaQuery.select(criteriaBuilder.count(countRoot));

    if (criteriaQuery.getGroupList() != null) {
        countCriteriaQuery.groupBy(criteriaQuery.getGroupList());
    }
    if (criteriaQuery.getGroupRestriction() != null) {
        countCriteriaQuery.having(criteriaQuery.getGroupRestriction());
    }
    if (criteriaQuery.getRestriction() != null) {
        countCriteriaQuery.where(criteriaQuery.getRestriction());
    }
    return entityManager.createQuery(countCriteriaQuery).setFlushMode(FlushModeType.COMMIT).getSingleResult();
}

From source file:net.groupbuy.dao.impl.MemberDaoImpl.java

public List<Object[]> findPurchaseList(Date beginDate, Date endDate, Integer count) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Object[]> criteriaQuery = criteriaBuilder.createQuery(Object[].class);
    Root<Member> member = criteriaQuery.from(Member.class);
    Join<Product, Order> orders = member.join("orders");
    criteriaQuery.multiselect(member.get("id"), member.get("username"), member.get("email"),
            member.get("point"), member.get("amount"), member.get("balance"),
            criteriaBuilder.sum(orders.<BigDecimal>get("amountPaid")));
    Predicate restrictions = criteriaBuilder.conjunction();
    if (beginDate != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.greaterThanOrEqualTo(orders.<Date>get("createDate"), beginDate));
    }/*from   ww  w .ja  v  a 2 s  .  co m*/
    if (endDate != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.lessThanOrEqualTo(orders.<Date>get("createDate"), endDate));
    }
    restrictions = criteriaBuilder.and(restrictions,
            criteriaBuilder.equal(orders.get("orderStatus"), OrderStatus.completed),
            criteriaBuilder.equal(orders.get("paymentStatus"), PaymentStatus.paid));
    criteriaQuery.where(restrictions);
    criteriaQuery.groupBy(member.get("id"), member.get("username"), member.get("email"), member.get("point"),
            member.get("amount"), member.get("balance"));
    criteriaQuery.orderBy(criteriaBuilder.desc(criteriaBuilder.sum(orders.<BigDecimal>get("amountPaid"))));
    TypedQuery<Object[]> query = entityManager.createQuery(criteriaQuery).setFlushMode(FlushModeType.COMMIT);
    if (count != null && count >= 0) {
        query.setMaxResults(count);
    }
    return query.getResultList();
}

From source file:org.easy.criteria.CriteriaProcessor.java

/**
 * Finds single tuple for the given criteria. Make sure you have provided
 * columns information in CriteriaContainer that you want in this tuple
 * result-set.//from w  w w . ja v  a2  s .  co m
 * 
 * @param criteria
 * @param lockMode
 * @return - A single tuple or null if no result was found.
 */
public <T> Tuple findUniqueTuple(CriteriaComposer<T> criteria, QueryProperties properties) {
    log.trace("CriteriaProcessor.findUniqueTuple");
    Preconditions.checkNotNull(criteria);

    Class<T> forClass = criteria.getEntityClass();

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteriaQuery = criteriaBuilder.createQuery(Tuple.class);

    log.debug("root =" + forClass.getName());
    Root<T> root = criteriaQuery.from(forClass);

    List<Predicate> wherePredicates = new ArrayList<Predicate>();
    List<Selection<?>> selectAttributes = new ArrayList<Selection<?>>();

    if (criteria != null) {
        criteria.generateJoins(root);
        criteria.generateSelect(criteriaBuilder, selectAttributes);
        criteria.generateWhere(criteriaBuilder, wherePredicates);
    }

    Preconditions.checkState(selectAttributes != null);
    Preconditions.checkArgument(selectAttributes.size() > 0, "No column name found for select clause. "
            + "Atleast one should be provided for Tuple result. Consider using findUniqueEntity instead.");

    criteriaQuery.multiselect(selectAttributes);

    criteriaQuery.where(wherePredicates.toArray(new Predicate[wherePredicates.size()]));

    TypedQuery<Tuple> query = entityManager.createQuery(criteriaQuery);

    if (properties != null)
        properties.applyProperties(query);

    return query.getSingleResult();
}

From source file:org.broadleafcommerce.core.catalog.dao.ProductDaoImpl.java

protected CriteriaQuery<Product> getCriteriaForActiveProducts(Date currentDate) {
    // Set up the criteria query that specifies we want to return Products
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Product> criteria = builder.createQuery(Product.class);

    // The root of our search is Product
    Root<ProductImpl> product = criteria.from(ProductImpl.class);

    // We need to filter on active date on the sku
    Join<Product, Sku> sku = product.join("defaultSku");
    product.fetch("defaultSku");

    // Product objects are what we want back
    criteria.select(product);//w  w w  . ja va 2  s  .  c o  m

    // Ensure the product is currently active
    List<Predicate> restrictions = new ArrayList<Predicate>();
    attachActiveRestriction(currentDate, product, sku, restrictions);

    // Add the restrictions to the criteria query
    criteria.where(restrictions.toArray(new Predicate[restrictions.size()]));

    //Add ordering so that paginated queries are consistent
    criteria.orderBy(builder.asc(product.get("id")));
    return criteria;
}

From source file:net.groupbuy.dao.impl.ReviewDaoImpl.java

public Page<Review> findPage(Member member, Product product, Type type, Boolean isShow, Pageable pageable) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Review> criteriaQuery = criteriaBuilder.createQuery(Review.class);
    Root<Review> root = criteriaQuery.from(Review.class);
    criteriaQuery.select(root);/* ww w . j a v a  2s  .co  m*/
    Predicate restrictions = criteriaBuilder.conjunction();
    if (member != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member));
    }
    if (product != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("product"), product));
    }
    if (type == Type.positive) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.ge(root.<Number>get("score"), 4));
    } else if (type == Type.moderate) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.<Number>get("score"), 3));
    } else if (type == Type.negative) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.le(root.<Number>get("score"), 2));
    }
    if (isShow != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isShow"), isShow));
    }
    criteriaQuery.where(restrictions);
    return super.findPage(criteriaQuery, pageable);
}

From source file:net.groupbuy.dao.impl.ReviewDaoImpl.java

public Long count(Member member, Product product, Type type, Boolean isShow) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Review> criteriaQuery = criteriaBuilder.createQuery(Review.class);
    Root<Review> root = criteriaQuery.from(Review.class);
    criteriaQuery.select(root);/*from   w  w w  .  ja  v  a2  s  .c o  m*/
    Predicate restrictions = criteriaBuilder.conjunction();
    if (member != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member));
    }
    if (product != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("product"), product));
    }
    if (type == Type.positive) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.ge(root.<Number>get("score"), 4));
    } else if (type == Type.moderate) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.<Number>get("score"), 3));
    } else if (type == Type.negative) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.le(root.<Number>get("score"), 2));
    }
    if (isShow != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isShow"), isShow));
    }
    criteriaQuery.where(restrictions);
    return super.count(criteriaQuery, null);
}

From source file:net.groupbuy.dao.impl.ReviewDaoImpl.java

public List<Review> findList(Member member, Product product, Type type, Boolean isShow, Integer count,
        List<Filter> filters, List<Order> orders) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Review> criteriaQuery = criteriaBuilder.createQuery(Review.class);
    Root<Review> root = criteriaQuery.from(Review.class);
    criteriaQuery.select(root);//from  w  w w  .  j av  a  2s  .c  om
    Predicate restrictions = criteriaBuilder.conjunction();
    if (member != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member));
    }
    if (product != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("product"), product));
    }
    if (type == Type.positive) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.ge(root.<Number>get("score"), 4));
    } else if (type == Type.moderate) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.<Number>get("score"), 3));
    } else if (type == Type.negative) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.le(root.<Number>get("score"), 2));
    }
    if (isShow != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isShow"), isShow));
    }
    criteriaQuery.where(restrictions);
    return super.findList(criteriaQuery, null, count, filters, orders);
}