Example usage for javax.persistence.criteria Expression in

List of usage examples for javax.persistence.criteria Expression in

Introduction

In this page you can find the example usage for javax.persistence.criteria Expression in.

Prototype

Predicate in(Expression<Collection<?>> values);

Source Link

Document

Create a predicate to test whether the expression is a member of the collection.

Usage

From source file:com.ocs.dynamo.dao.query.JpaQueryBuilder.java

/**
 * Creates a query that fetches objects based on their IDs
 * //from  w  w w.j  a v  a 2 s .  c om
 * @param entityManager
 *            the entity manager
 * @param entityClass
 *            the entity class
 * @param ids
 *            the IDs of the desired entities
 * @param sortOrders
 *            the sorting information
 * @param fetchJoins
 *            the desired fetch joins
 * @return
 */
public static <ID, T> CriteriaQuery<T> createFetchQuery(EntityManager entityManager, Class<T> entityClass,
        List<ID> ids, SortOrders sortOrders, FetchJoinInformation[] fetchJoins) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<T> cq = builder.createQuery(entityClass);
    Root<T> root = cq.from(entityClass);

    boolean distinct = addFetchJoinInformation(root, fetchJoins);

    Expression<String> exp = root.get(DynamoConstants.ID);
    cq.where(exp.in(ids));
    cq.distinct(distinct);

    return addSortInformation(builder, cq, root, sortOrders == null ? null : sortOrders.toArray());
}

From source file:com.ocs.dynamo.dao.query.JpaQueryBuilder.java

/**
 * Creates a JPA2 predicate based on a Filter
 * //from www . ja v  a2  s. co  m
 * @param filter
 *            the filter
 * @param builder
 *            the criteria builder
 * @param root
 *            the entity root
 * @return
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
private static Predicate createPredicate(Filter filter, CriteriaBuilder builder, Root<?> root) {
    if (filter == null) {
        return null;
    }

    if (filter instanceof And) {
        return createAndPredicate(builder, root, filter);
    } else if (filter instanceof Or) {
        return createOrPredicate(builder, root, filter);
    } else if (filter instanceof Not) {
        Not not = (Not) filter;
        return builder.not(createPredicate(not.getFilter(), builder, root));
    } else if (filter instanceof Between) {
        Between between = (Between) filter;
        Expression property = getPropertyPath(root, between.getPropertyId());
        return builder.between(property, (Comparable) between.getStartValue(),
                (Comparable) between.getEndValue());
    } else if (filter instanceof Compare) {
        return createComparePredicate(builder, root, filter);
    } else if (filter instanceof IsNull) {
        IsNull isNull = (IsNull) filter;
        return builder.isNull(getPropertyPath(root, isNull.getPropertyId()));
    } else if (filter instanceof Like) {
        return createLikePredicate(builder, root, filter);
    } else if (filter instanceof Contains) {
        Contains contains = (Contains) filter;
        return builder.isMember(contains.getValue(),
                (Expression) getPropertyPath(root, contains.getPropertyId()));
    } else if (filter instanceof In) {
        In in = (In) filter;
        if (in.getValues() != null && !in.getValues().isEmpty()) {
            Expression exp = getPropertyPath(root, in.getPropertyId());
            return exp.in(in.getValues());
        } else {
            Expression exp = getPropertyPath(root, in.getPropertyId());
            return exp.in(Lists.newArrayList(-1));
        }
    } else if (filter instanceof Modulo) {
        return createModuloPredicate(builder, root, filter);
    }

    throw new UnsupportedOperationException("Filter: " + filter.getClass().getName() + " not recognized");
}

From source file:dk.dma.msinm.common.db.PredicateHelper.java

/**
 * If values is defined, matches the attribute with any of the values.
 * If values is undefined (null or empty) this predicate yields false.
 *
 * @param attr the attribute//from   ww  w  .jav a 2  s .  com
 * @param values the values to match
 */
public <V> PredicateHelper<T> in(Expression<V> attr, Collection<V> values) {
    if (values != null && values.size() > 0) {
        where.add(attr.in(values));
    } else {
        where.add(cb.disjunction()); // Always false
    }
    return this;
}

From source file:com.aimdek.ccm.dao.impl.StatementRepositoryImpl.java

/**
 * Adds the filter criteria./*from  w  w w  .  ja va2 s . com*/
 *
 * @param userId
 *            the user id
 * @param filters
 *            the filters
 * @param builder
 *            the builder
 * @param root
 *            the root
 * @param query
 *            the query
 */
private void addFilterCriteria(long userId, Map<String, Object> filters, CriteriaBuilder builder,
        Root<Statement> root, CriteriaQuery query) {

    List<Predicate> predicates = new ArrayList<Predicate>();
    if (!filters.isEmpty()) {
        for (Entry<String, Object> entry : filters.entrySet()) {
            if (CommonUtil.isNotNull(root.get(entry.getKey()))) {
                predicates.add(builder.like(root.<String>get(entry.getKey()), entry.getValue() + MODULO));
            }
        }
    }
    if (CommonUtil.isNotNull(userId)) {
        User user = userRepository.findById(userId);
        if (CommonUtil.isNotNull(user) && user.getRole().equals(ROLE_CUSTOMER)) {
            Expression<String> exp = root.get(FIELD_CONSTANT_CREDIT_CARD_ID);
            Predicate predicate = exp.in(retrieveCreditCardIdFromUserId(userId));
            predicates.add(predicate);
        }
    }

    query.where(predicates.toArray(new Predicate[] {}));
}

From source file:gov.guilin.dao.impl.ProductDaoImpl.java

public Page<Product> findPage(ProductCategory productCategory, Brand brand, Promotion promotion, List<Tag> tags,
        Map<Attribute, String> attributeValue, BigDecimal startPrice, BigDecimal endPrice, Boolean isMarketable,
        Boolean isList, Boolean isTop, Boolean isGift, Boolean isOutOfStock, Boolean isStockAlert,
        OrderType orderType, Pageable pageable, Set<Supplier> suppliers) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Product> criteriaQuery = criteriaBuilder.createQuery(Product.class);
    Root<Product> root = criteriaQuery.from(Product.class);
    criteriaQuery.select(root);/*from w w w .  j av  a 2s .  com*/
    Predicate restrictions = criteriaBuilder.conjunction();
    if (productCategory != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.or(criteriaBuilder.equal(root.get("productCategory"), productCategory),
                        criteriaBuilder.like(root.get("productCategory").<String>get("treePath"),
                                "%" + ProductCategory.TREE_PATH_SEPARATOR + productCategory.getId()
                                        + ProductCategory.TREE_PATH_SEPARATOR + "%")));
    }
    if (brand != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("brand"), brand));
    }
    if (promotion != null) {
        Subquery<Product> subquery1 = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot1 = subquery1.from(Product.class);
        subquery1.select(subqueryRoot1);
        subquery1.where(criteriaBuilder.equal(subqueryRoot1, root),
                criteriaBuilder.equal(subqueryRoot1.join("promotions"), promotion));

        Subquery<Product> subquery2 = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot2 = subquery2.from(Product.class);
        subquery2.select(subqueryRoot2);
        subquery2.where(criteriaBuilder.equal(subqueryRoot2, root),
                criteriaBuilder.equal(subqueryRoot2.join("productCategory").join("promotions"), promotion));

        Subquery<Product> subquery3 = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot3 = subquery3.from(Product.class);
        subquery3.select(subqueryRoot3);
        subquery3.where(criteriaBuilder.equal(subqueryRoot3, root),
                criteriaBuilder.equal(subqueryRoot3.join("brand").join("promotions"), promotion));

        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.exists(subquery1),
                criteriaBuilder.exists(subquery2), criteriaBuilder.exists(subquery3)));
    }
    if (tags != null && !tags.isEmpty()) {
        Subquery<Product> subquery = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot = subquery.from(Product.class);
        subquery.select(subqueryRoot);
        subquery.where(criteriaBuilder.equal(subqueryRoot, root), subqueryRoot.join("tags").in(tags));
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.exists(subquery));
    }
    if (attributeValue != null) {
        for (Entry<Attribute, String> entry : attributeValue.entrySet()) {
            String propertyName = Product.ATTRIBUTE_VALUE_PROPERTY_NAME_PREFIX
                    + entry.getKey().getPropertyIndex();
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.equal(root.get(propertyName), entry.getValue()));
        }
    }
    if (startPrice != null && endPrice != null && startPrice.compareTo(endPrice) > 0) {
        BigDecimal temp = startPrice;
        startPrice = endPrice;
        endPrice = temp;
    }
    if (startPrice != null && startPrice.compareTo(new BigDecimal(0)) >= 0) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.ge(root.<Number>get("price"), startPrice));
    }
    if (endPrice != null && endPrice.compareTo(new BigDecimal(0)) >= 0) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.le(root.<Number>get("price"), endPrice));
    }
    if (isMarketable != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isMarketable"), isMarketable));
    }
    if (isList != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isList"), isList));
    }
    if (isTop != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isTop"), isTop));
    }
    if (isGift != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isGift"), isGift));
    }
    Path<Integer> stock = root.get("stock");
    Path<Integer> allocatedStock = root.get("allocatedStock");
    if (isOutOfStock != null) {
        if (isOutOfStock) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock),
                    criteriaBuilder.lessThanOrEqualTo(stock, allocatedStock));
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.isNull(stock),
                    criteriaBuilder.greaterThan(stock, allocatedStock)));
        }
    }
    if (isStockAlert != null) {
        Setting setting = SettingUtils.get();
        if (isStockAlert) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock),
                    criteriaBuilder.lessThanOrEqualTo(stock,
                            criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount())));
        } else {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.or(criteriaBuilder.isNull(stock), criteriaBuilder.greaterThan(stock,
                            criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount()))));
        }
    }

    //??ADDbyDanielChen 20140502
    if ((suppliers != null) && !(suppliers.isEmpty())) {
        Expression<Supplier> exp = root.get("supplier");
        restrictions = criteriaBuilder.and(restrictions, exp.in(suppliers));
    }

    criteriaQuery.where(restrictions);
    List<Order> orders = pageable.getOrders();
    if (orderType == OrderType.priceAsc) {
        orders.add(Order.asc("price"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.priceDesc) {
        orders.add(Order.desc("price"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.salesDesc) {
        orders.add(Order.desc("sales"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.scoreDesc) {
        orders.add(Order.desc("score"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.dateDesc) {
        orders.add(Order.desc("createDate"));
    } else {
        orders.add(Order.desc("isTop"));
        orders.add(Order.desc("modifyDate"));
    }
    return super.findPage(criteriaQuery, pageable);
}

From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java

private void createPredicateResourceId(CriteriaBuilder builder, CriteriaQuery<?> cq,
        List<Predicate> thePredicates, Expression<Long> theExpression) {
    if (myParams.isPersistResults()) {
        if (mySearchEntity.getTotalCount() > -1) {
            Subquery<Long> subQ = cq.subquery(Long.class);
            Root<SearchResult> subQfrom = subQ.from(SearchResult.class);
            subQ.select(subQfrom.get("myResourcePid").as(Long.class));
            Predicate subQname = builder.equal(subQfrom.get("mySearch"), mySearchEntity);
            subQ.where(subQname);/*  ww w.j  a v a  2 s.  co m*/

            thePredicates.add(theExpression.in(subQ));
        }
    } else {
        if (myPids != null) {
            thePredicates.add(theExpression.in(myPids));
        }
    }

}

From source file:gov.osti.services.Metadata.java

/**
 * Acquire a List of records in pending ("Submitted") state, to be approved
 * for indexing and searching.// www . j  a  v  a  2s  . com
 *
 * JSON response is of the form:
 *
 * {"records":[{"code_id":n, ...} ],
 *  "start":0, "rows":20, "total":100}
 *
 * Where records is an array of DOECodeMetadata JSON, start is the beginning
 * row number, rows is the number requested (or total if less available),
 * and total is the total number of rows matching the filter.
 *
 * Return Codes:
 * 200 - OK, JSON is returned as above
 * 401 - Unauthorized, login is required
 * 403 - Forbidden, insufficient privileges (role required)
 * 500 - unexpected error
 *
 * @param start the starting row number (from 0)
 * @param rows number of rows desired (0 is unlimited)
 * @param siteCode (optional) a SITE OWNERSHIP CODE to filter by site
 * @param state the WORKFLOW STATE if desired (default Submitted and Announced). One of
 * Approved, Saved, Submitted, or Announced, if supplied.
 * @return JSON of a records response
 */
@GET
@Path("/projects/pending")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@RequiresAuthentication
@RequiresRoles("OSTI")
public Response listProjectsPending(@QueryParam("start") int start, @QueryParam("rows") int rows,
        @QueryParam("site") String siteCode, @QueryParam("state") String state) {
    EntityManager em = DoeServletContextListener.createEntityManager();

    try {
        // get a JPA CriteriaBuilder instance
        CriteriaBuilder cb = em.getCriteriaBuilder();
        // create a CriteriaQuery for the COUNT
        CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
        Root<DOECodeMetadata> md = countQuery.from(DOECodeMetadata.class);
        countQuery.select(cb.count(md));

        Expression<String> workflowStatus = md.get("workflowStatus");
        Expression<String> siteOwnershipCode = md.get("siteOwnershipCode");

        // default requested STATE; take Submitted and Announced as the default values if not supplied
        List<DOECodeMetadata.Status> requestedStates = new ArrayList();
        String queryState = (StringUtils.isEmpty(state)) ? "" : state.toLowerCase();
        switch (queryState) {
        case "approved":
            requestedStates.add(DOECodeMetadata.Status.Approved);
            break;
        case "saved":
            requestedStates.add(DOECodeMetadata.Status.Saved);
            break;
        case "submitted":
            requestedStates.add(DOECodeMetadata.Status.Submitted);
            break;
        case "announced":
            requestedStates.add(DOECodeMetadata.Status.Announced);
            break;
        default:
            requestedStates.add(DOECodeMetadata.Status.Submitted);
            requestedStates.add(DOECodeMetadata.Status.Announced);
            break;
        }

        Predicate statusPredicate = workflowStatus.in(requestedStates);
        ParameterExpression<String> site = cb.parameter(String.class, "site");

        if (null == siteCode) {
            countQuery.where(statusPredicate);
        } else {
            countQuery.where(cb.and(statusPredicate, cb.equal(siteOwnershipCode, site)));
        }
        // query for the COUNT
        TypedQuery<Long> cq = em.createQuery(countQuery);
        cq.setParameter("status", requestedStates);
        if (null != siteCode)
            cq.setParameter("site", siteCode);

        long rowCount = cq.getSingleResult();
        // rows count should be less than 100 for pagination; 0 is a special case
        rows = (rows > 100) ? 100 : rows;

        // create a CriteriaQuery for the ROWS
        CriteriaQuery<DOECodeMetadata> rowQuery = cb.createQuery(DOECodeMetadata.class);
        rowQuery.select(md);

        if (null == siteCode) {
            rowQuery.where(statusPredicate);
        } else {
            rowQuery.where(cb.and(statusPredicate, cb.equal(siteOwnershipCode, site)));
        }

        TypedQuery<DOECodeMetadata> rq = em.createQuery(rowQuery);
        rq.setParameter("status", requestedStates);
        if (null != siteCode)
            rq.setParameter("site", siteCode);
        rq.setFirstResult(start);
        if (0 != rows)
            rq.setMaxResults(rows);

        RecordsList records = new RecordsList(rq.getResultList());
        records.setTotal(rowCount);
        records.setStart(start);

        return Response.ok().entity(mapper.valueToTree(records).toString()).build();
    } finally {
        em.close();
    }
}

From source file:org.finra.herd.dao.impl.BusinessObjectDefinitionDaoImpl.java

@Override
public List<BusinessObjectDefinitionEntity> getAllBusinessObjectDefinitionsByIds(List<Integer> ids) {
    // Create the criteria builder and a tuple style criteria query.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<BusinessObjectDefinitionEntity> criteria = builder
            .createQuery(BusinessObjectDefinitionEntity.class);

    // The criteria root is the business object definition.
    Root<BusinessObjectDefinitionEntity> businessObjectDefinitionEntityRoot = criteria
            .from(BusinessObjectDefinitionEntity.class);

    // Create the standard restrictions (i.e. the standard where clauses).
    Expression<Integer> expression = businessObjectDefinitionEntityRoot.get(BusinessObjectDefinitionEntity_.id);
    Predicate queryRestriction = expression.in(ids);

    criteria.select(businessObjectDefinitionEntityRoot).where(queryRestriction);

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

From source file:org.finra.herd.dao.impl.TagDaoImpl.java

@Override
public List<TagEntity> getTagsByIds(List<Integer> ids) {
    // Create the criteria builder and a tuple style criteria query.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<TagEntity> criteria = builder.createQuery(TagEntity.class);

    // The criteria root is the tag entity.
    Root<TagEntity> tagEntityRoot = criteria.from(TagEntity.class);

    // Create the standard restrictions (i.e. the standard where clauses).
    Expression<Integer> expression = tagEntityRoot.get(TagEntity_.id);
    Predicate queryRestriction = expression.in(ids);

    criteria.select(tagEntityRoot).where(queryRestriction);

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

From source file:org.kuali.rice.kew.rule.dao.impl.RuleDAOJpa.java

private Subquery<RuleResponsibilityBo> addResponsibilityCriteria(CriteriaQuery<RuleBaseValues> query,
        Collection<String> workgroupIds, String workflowId, Collection actionRequestCodes, Boolean searchUser,
        Boolean searchUserInWorkgroups) {

    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    Subquery<RuleResponsibilityBo> subquery = query.subquery(RuleResponsibilityBo.class);
    Root fromResp = subquery.from(RuleResponsibilityBo.class);

    List<javax.persistence.criteria.Predicate> respPredicates = new ArrayList<javax.persistence.criteria.Predicate>();

    List<javax.persistence.criteria.Predicate> ruleRespNamePredicates = new ArrayList<javax.persistence.criteria.Predicate>();

    List<javax.persistence.criteria.Predicate> userNamePreds = new ArrayList<javax.persistence.criteria.Predicate>();

    List<javax.persistence.criteria.Predicate> workgroupPreds = new ArrayList<javax.persistence.criteria.Predicate>();

    if ((actionRequestCodes != null) && (!actionRequestCodes.isEmpty())) {
        Expression<String> exp = fromResp.get("actionRequestedCd");
        javax.persistence.criteria.Predicate actionRequestPredicate = exp.in(actionRequestCodes);

        respPredicates.add(actionRequestPredicate);
    }/* w  w w . ja  v a 2  s .  c om*/

    if (!org.apache.commons.lang.StringUtils.isEmpty(workflowId)) {
        // workflow user id exists
        if (searchUser != null && searchUser) {
            // searching user wishes to search for rules specific to user
            userNamePreds.add(cb.like(fromResp.get("ruleResponsibilityName"), workflowId));
            userNamePreds.add(cb.equal(fromResp.get("ruleResponsibilityType"),
                    KewApiConstants.RULE_RESPONSIBILITY_WORKFLOW_ID));

            javax.persistence.criteria.Predicate[] preds = userNamePreds
                    .toArray(new javax.persistence.criteria.Predicate[userNamePreds.size()]);
            ruleRespNamePredicates.add(cb.and(preds));

        }
        if ((searchUserInWorkgroups != null && searchUserInWorkgroups) && (workgroupIds != null)
                && (!workgroupIds.isEmpty())) {
            // at least one workgroup id exists and user wishes to search on workgroups

            Expression<String> exp = fromResp.get("ruleResponsibilityName");
            javax.persistence.criteria.Predicate groupIdPredicate = exp.in(workgroupIds);
            workgroupPreds.add(groupIdPredicate);
            workgroupPreds.add(cb.equal(fromResp.get("ruleResponsibilityType"),
                    KewApiConstants.RULE_RESPONSIBILITY_GROUP_ID));
            javax.persistence.criteria.Predicate[] preds = workgroupPreds
                    .toArray(new javax.persistence.criteria.Predicate[workgroupPreds.size()]);
            ruleRespNamePredicates.add(cb.and(preds));
        }
    } else if ((workgroupIds != null) && (workgroupIds.size() == 1)) {
        // no user and one workgroup id
        workgroupPreds.add(cb.like(fromResp.get("ruleResponsibilityName"), workgroupIds.iterator().next()));
        workgroupPreds.add(
                cb.equal(fromResp.get("ruleResponsibilityType"), KewApiConstants.RULE_RESPONSIBILITY_GROUP_ID));
        javax.persistence.criteria.Predicate[] preds = workgroupPreds
                .toArray(new javax.persistence.criteria.Predicate[workgroupPreds.size()]);
        ruleRespNamePredicates.add(cb.and(preds));

    } else if ((workgroupIds != null) && (workgroupIds.size() > 1)) {
        // no user and more than one workgroup id

        Expression<String> exp = fromResp.get("ruleResponsibilityName");
        javax.persistence.criteria.Predicate groupIdPredicate = exp.in(workgroupIds);
        workgroupPreds.add(
                cb.equal(fromResp.get("ruleResponsibilityType"), KewApiConstants.RULE_RESPONSIBILITY_GROUP_ID));
        javax.persistence.criteria.Predicate[] preds = workgroupPreds
                .toArray(new javax.persistence.criteria.Predicate[workgroupPreds.size()]);
        ruleRespNamePredicates.add(cb.and(preds));
    }

    if (!ruleRespNamePredicates.isEmpty()) {
        javax.persistence.criteria.Predicate[] preds = ruleRespNamePredicates
                .toArray(new javax.persistence.criteria.Predicate[ruleRespNamePredicates.size()]);
        respPredicates.add(cb.or(preds));
    }

    if (!respPredicates.isEmpty()) {

        javax.persistence.criteria.Predicate[] preds = respPredicates
                .toArray(new javax.persistence.criteria.Predicate[respPredicates.size()]);
        subquery.where(preds);
        subquery.select(fromResp.get("ruleBaseValuesId"));
        return subquery;
    }
    return null;
}