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:ca.uhn.fhir.jpa.dao.SearchBuilder.java

private void addPredicateDate(String theParamName, List<? extends IQueryParameterType> theList) {

    if (Boolean.TRUE.equals(theList.get(0).getMissing())) {
        addPredicateParamMissing("myParamsDate", theParamName, ResourceIndexedSearchParamDate.class);
        return;/*from w w w. ja v a 2 s.c  o m*/
    }

    CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
    CriteriaQuery<Long> cq = builder.createQuery(Long.class);
    Root<ResourceIndexedSearchParamDate> from = cq.from(ResourceIndexedSearchParamDate.class);
    cq.select(from.get("myResourcePid").as(Long.class));

    List<Predicate> codePredicates = new ArrayList<Predicate>();
    for (IQueryParameterType nextOr : theList) {
        if (addPredicateMissingFalseIfPresent(builder, theParamName, from, codePredicates, nextOr)) {
            continue;
        }

        IQueryParameterType params = nextOr;
        Predicate p = createPredicateDate(builder, from, params);
        codePredicates.add(p);
    }

    Predicate masterCodePredicate = builder.or(toArray(codePredicates));

    List<Predicate> predicates = new ArrayList<Predicate>();
    predicates.add(builder.equal(from.get("myResourceType"), myResourceName));
    predicates.add(builder.equal(from.get("myParamName"), theParamName));
    createPredicateResourceId(builder, cq, predicates, from.get("myResourcePid").as(Long.class));
    createPredicateLastUpdatedForIndexedSearchParam(builder, from, predicates);
    predicates.add(masterCodePredicate);

    cq.where(builder.and(toArray(predicates)));

    TypedQuery<Long> q = myEntityManager.createQuery(cq);
    doSetPids(q.getResultList());
}

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

private void addPredicateComposite(RuntimeSearchParam theParamDef,
        List<? extends IQueryParameterType> theNextAnd) {
    // TODO: fail if missing is set for a composite query

    CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
    CriteriaQuery<Long> cq = builder.createQuery(Long.class);
    Root<ResourceTable> from = cq.from(ResourceTable.class);
    cq.select(from.get("myId").as(Long.class));

    IQueryParameterType or = theNextAnd.get(0);
    if (!(or instanceof CompositeParam<?, ?>)) {
        throw new InvalidRequestException("Invalid type for composite param (must be "
                + CompositeParam.class.getSimpleName() + ": " + or.getClass());
    }/*from w ww . j a v a  2  s  . co  m*/
    CompositeParam<?, ?> cp = (CompositeParam<?, ?>) or;

    List<Predicate> predicates = new ArrayList<Predicate>();
    predicates.add(builder.equal(from.get("myResourceType"), myResourceName));

    RuntimeSearchParam left = theParamDef.getCompositeOf().get(0);
    IQueryParameterType leftValue = cp.getLeftValue();
    predicates.add(createCompositeParamPart(builder, from, left, leftValue));

    RuntimeSearchParam right = theParamDef.getCompositeOf().get(1);
    IQueryParameterType rightValue = cp.getRightValue();
    predicates.add(createCompositeParamPart(builder, from, right, rightValue));

    createPredicateResourceId(builder, cq, predicates, from.get("myId").as(Long.class));
    cq.where(builder.and(toArray(predicates)));

    TypedQuery<Long> q = myEntityManager.createQuery(cq);
    doSetPids(q.getResultList());

}

From source file:com.yunguchang.data.ApplicationRepository.java

public List<TBusApplyinfoEntity> getApplicationForSync(DateTime startTime, DateTime endTime, String status,
        Boolean isSend, PrincipalExt principalExt) {
    if (startTime == null) {
        startTime = DateTimeUtil.appStartTime;
    }/*from w w w . jav  a 2  s  .  c  om*/
    if (endTime == null) {
        endTime = DateTimeUtil.appEndTime;
    }
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<TBusApplyinfoEntity> cq = cb.createQuery(TBusApplyinfoEntity.class);
    Root<TBusApplyinfoEntity> applyRoot = cq.from(TBusApplyinfoEntity.class);
    applyRoot.fetch(TBusApplyinfoEntity_.passenger);
    applyRoot.fetch(TBusApplyinfoEntity_.coordinator);
    applyRoot.fetch(TBusApplyinfoEntity_.department);
    applyRoot.fetch(TBusApplyinfoEntity_.senduser, JoinType.LEFT);

    Predicate predicate = cb.conjunction();

    predicate = cb.and(predicate, cb.or(cb.isNull(applyRoot.get(TBusApplyinfoEntity_.updateBySync)),
            cb.isFalse(applyRoot.get(TBusApplyinfoEntity_.updateBySync))));
    if (status != null) {
        predicate = cb.and(predicate,
                // "2" ->  "3" -> ? "4" -> ?
                cb.equal(applyRoot.get(TBusApplyinfoEntity_.status), status));
    }
    if (isSend != null && isSend) {
        predicate = cb.and(predicate, cb.equal(applyRoot.get(TBusApplyinfoEntity_.issend), "1") // 
        );
    }
    if ("4".equals(status)) {
        Fetch<TBusApplyinfoEntity, TBusScheduleRelaEntity> scheduleFetch = applyRoot
                .fetch(TBusApplyinfoEntity_.schedule, JoinType.LEFT);
        Join<TBusApplyinfoEntity, TBusScheduleRelaEntity> scheduleJoin = (Join<TBusApplyinfoEntity, TBusScheduleRelaEntity>) scheduleFetch;
        scheduleJoin.fetch(TBusScheduleRelaEntity_.reciveuser, JoinType.LEFT);
        Fetch<TBusScheduleRelaEntity, TBusScheduleCarEntity> fetchScheduleCar = scheduleFetch
                .fetch(TBusScheduleRelaEntity_.scheduleCars, JoinType.LEFT);
        fetchScheduleCar.fetch(TBusScheduleCarEntity_.car, JoinType.LEFT).fetch(TAzCarinfoEntity_.depot,
                JoinType.LEFT);
        fetchScheduleCar.fetch(TBusScheduleCarEntity_.driver, JoinType.LEFT)
                .fetch(TRsDriverinfoEntity_.department, JoinType.LEFT);
        predicate = cb.and(predicate,
                cb.or(cb.between(applyRoot.get(TBusApplyinfoEntity_.updatedate), startTime, endTime),
                        cb.between(scheduleJoin.get(TBusScheduleRelaEntity_.updatedate), startTime, endTime)));
    } else {
        predicate = cb.and(predicate,
                cb.between(applyRoot.get(TBusApplyinfoEntity_.updatedate), startTime, endTime));
    }

    cq.where(predicate);

    TypedQuery<TBusApplyinfoEntity> query = em.createQuery(cq);

    //        applySecurityFilter("applications", principalExt);
    return query.getResultList();
}

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

private void addPredicateTag(List<List<? extends IQueryParameterType>> theList, String theParamName,
        DateRangeParam theLastUpdated) {
    TagTypeEnum tagType;//from w w  w  .jav  a  2s.  c  om
    if (Constants.PARAM_TAG.equals(theParamName)) {
        tagType = TagTypeEnum.TAG;
    } else if (Constants.PARAM_PROFILE.equals(theParamName)) {
        tagType = TagTypeEnum.PROFILE;
    } else if (Constants.PARAM_SECURITY.equals(theParamName)) {
        tagType = TagTypeEnum.SECURITY_LABEL;
    } else {
        throw new IllegalArgumentException("Param name: " + theParamName); // shouldn't happen
    }

    /*
     * CriteriaBuilder builder = myEntityManager.getCriteriaBuilder(); CriteriaQuery<Long> cq =
     * builder.createQuery(Long.class); Root<ResourceTable> from = cq.from(ResourceTable.class);
     * cq.select(from.get("myId").as(Long.class));
     * 
     * Subquery<Long> subQ = cq.subquery(Long.class); Root<? extends BaseResourceIndexedSearchParam> subQfrom =
     * subQ.from(theParamTable); subQ.select(subQfrom.get("myResourcePid").as(Long.class));
     * Predicate subQname = builder.equal(subQfrom.get("myParamName"), theParamName); Predicate subQtype =
     * builder.equal(subQfrom.get("myResourceType"), myResourceName);
     * subQ.where(builder.and(subQtype, subQname));
     * 
     * List<Predicate> predicates = new ArrayList<Predicate>();
     * predicates.add(builder.not(builder.in(from.get("myId")).value(subQ)));
     * predicates.add(builder.equal(from.get("myResourceType"),
     * myResourceName)); predicates.add(builder.isNull(from.get("myDeleted"))); createPredicateResourceId(builder, cq,
     * predicates, from.get("myId").as(Long.class));
     */

    List<Pair<String, String>> notTags = Lists.newArrayList();
    for (List<? extends IQueryParameterType> nextAndParams : theList) {
        for (IQueryParameterType nextOrParams : nextAndParams) {
            if (nextOrParams instanceof TokenParam) {
                TokenParam param = (TokenParam) nextOrParams;
                if (param.getModifier() == TokenParamModifier.NOT) {
                    if (isNotBlank(param.getSystem()) || isNotBlank(param.getValue())) {
                        notTags.add(Pair.of(param.getSystem(), param.getValue()));
                    }
                }
            }
        }
    }

    /*
     * We have a parameter of ResourceType?_tag:not=foo This means match resources that don't have the given tag(s)
     */
    if (notTags.isEmpty() == false) {
        // CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
        // CriteriaQuery<Long> cq = builder.createQuery(Long.class);
        // Root<ResourceTable> from = cq.from(ResourceTable.class);
        // cq.select(from.get("myId").as(Long.class));
        //
        // Subquery<Long> subQ = cq.subquery(Long.class);
        // Root<ResourceTag> subQfrom = subQ.from(ResourceTag.class);
        // subQ.select(subQfrom.get("myResourceId").as(Long.class));
        // Predicate subQname = builder.equal(subQfrom.get("myParamName"), theParamName);
        // Predicate subQtype = builder.equal(subQfrom.get("myResourceType"), myResourceName);
        // subQ.where(builder.and(subQtype, subQname));
        //
        // List<Predicate> predicates = new ArrayList<Predicate>();
        // predicates.add(builder.not(builder.in(from.get("myId")).value(subQ)));
        // predicates.add(builder.equal(from.get("myResourceType"), myResourceName));
        // predicates.add(builder.isNull(from.get("myDeleted")));
        // createPredicateResourceId(builder, cq, predicates, from.get("myId").as(Long.class));
    }

    for (List<? extends IQueryParameterType> nextAndParams : theList) {
        boolean haveTags = false;
        for (IQueryParameterType nextParamUncasted : nextAndParams) {
            if (nextParamUncasted instanceof TokenParam) {
                TokenParam nextParam = (TokenParam) nextParamUncasted;
                if (isNotBlank(nextParam.getValue())) {
                    haveTags = true;
                } else if (isNotBlank(nextParam.getSystem())) {
                    throw new InvalidRequestException("Invalid " + theParamName
                            + " parameter (must supply a value/code and not just a system): "
                            + nextParam.getValueAsQueryToken(myContext));
                }
            } else {
                UriParam nextParam = (UriParam) nextParamUncasted;
                if (isNotBlank(nextParam.getValue())) {
                    haveTags = true;
                }
            }
        }
        if (!haveTags) {
            continue;
        }

        CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();

        boolean paramInverted = false;
        List<Pair<String, String>> tokens = Lists.newArrayList();
        for (IQueryParameterType nextOrParams : nextAndParams) {
            String code;
            String system;
            if (nextOrParams instanceof TokenParam) {
                TokenParam nextParam = (TokenParam) nextOrParams;
                code = nextParam.getValue();
                system = nextParam.getSystem();
                if (nextParam.getModifier() == TokenParamModifier.NOT) {
                    paramInverted = true;
                }
            } else {
                UriParam nextParam = (UriParam) nextOrParams;
                code = nextParam.getValue();
                system = null;
            }

            if (isNotBlank(code)) {
                tokens.add(Pair.of(system, code));
            }
        }

        if (tokens.isEmpty()) {
            continue;
        }

        if (paramInverted) {
            ourLog.debug("Searching for _tag:not");

            CriteriaQuery<Long> cq = builder.createQuery(Long.class);
            Root<ResourceTable> newFrom = cq.from(ResourceTable.class);

            Subquery<Long> subQ = cq.subquery(Long.class);
            Root<ResourceTag> subQfrom = subQ.from(ResourceTag.class);
            subQ.select(subQfrom.get("myResourceId").as(Long.class));

            cq.select(newFrom.get("myId").as(Long.class));

            List<Predicate> andPredicates = new ArrayList<Predicate>();
            andPredicates = new ArrayList<Predicate>();
            andPredicates.add(builder.equal(newFrom.get("myResourceType"), myResourceName));
            andPredicates.add(builder.not(builder.in(newFrom.get("myId")).value(subQ)));

            Subquery<Long> defJoin = subQ.subquery(Long.class);
            Root<TagDefinition> defJoinFrom = defJoin.from(TagDefinition.class);
            defJoin.select(defJoinFrom.get("myId").as(Long.class));

            subQ.where(subQfrom.get("myTagId").as(Long.class).in(defJoin));

            List<Predicate> orPredicates = createPredicateTagList(defJoinFrom, builder, tagType, tokens);
            defJoin.where(toArray(orPredicates));

            cq.where(toArray(andPredicates));

            TypedQuery<Long> q = myEntityManager.createQuery(cq);
            Set<Long> pids = new HashSet<Long>(q.getResultList());
            doSetPids(pids);
            continue;
        }

        CriteriaQuery<Long> cq = builder.createQuery(Long.class);
        Root<ResourceTag> from = cq.from(ResourceTag.class);
        List<Predicate> andPredicates = new ArrayList<Predicate>();
        andPredicates.add(builder.equal(from.get("myResourceType"), myResourceName));
        From<ResourceTag, TagDefinition> defJoin = from.join("myTag");

        Join<?, ResourceTable> defJoin2 = from.join("myResource");

        Predicate notDeletedPredicatePrediate = builder.isNull(defJoin2.get("myDeleted"));
        andPredicates.add(notDeletedPredicatePrediate);

        List<Predicate> orPredicates = createPredicateTagList(defJoin, builder, tagType, tokens);
        andPredicates.add(builder.or(toArray(orPredicates)));

        if (theLastUpdated != null) {
            andPredicates.addAll(createLastUpdatedPredicates(theLastUpdated, builder, defJoin2));
        }

        createPredicateResourceId(builder, cq, andPredicates, from.get("myResourceId").as(Long.class));
        Predicate masterCodePredicate = builder.and(toArray(andPredicates));

        cq.select(from.get("myResourceId").as(Long.class));
        cq.where(masterCodePredicate);

        TypedQuery<Long> q = myEntityManager.createQuery(cq);
        Set<Long> pids = new HashSet<Long>(q.getResultList());
        doSetPids(pids);
    }

}

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

private void addPredicateLanguage(List<List<? extends IQueryParameterType>> theList) {
    for (List<? extends IQueryParameterType> nextList : theList) {

        CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
        CriteriaQuery<Long> cq = builder.createQuery(Long.class);
        Root<ResourceTable> from = cq.from(ResourceTable.class);
        cq.select(from.get("myId").as(Long.class));

        Set<String> values = new HashSet<String>();
        for (IQueryParameterType next : nextList) {
            if (next instanceof StringParam) {
                String nextValue = ((StringParam) next).getValue();
                if (isBlank(nextValue)) {
                    continue;
                }//from   w  w w  . j a v a 2  s. co m
                values.add(nextValue);
            } else {
                throw new InternalErrorException(
                        "Lanugage parameter must be of type " + StringParam.class.getCanonicalName() + " - Got "
                                + next.getClass().getCanonicalName());
            }
        }

        if (values.isEmpty()) {
            continue;
        }

        List<Predicate> predicates = new ArrayList<Predicate>();
        predicates.add(builder.equal(from.get("myResourceType"), myResourceName));
        predicates.add(from.get("myLanguage").as(String.class).in(values));
        createPredicateResourceId(builder, cq, predicates, from.get("myId").as(Long.class));
        createPredicateLastUpdatedForResourceTable(builder, from, predicates);

        predicates.add(builder.isNull(from.get("myDeleted")));

        cq.where(toArray(predicates));

        TypedQuery<Long> q = myEntityManager.createQuery(cq);
        doSetPids(q.getResultList());
        if (doHaveNoResults()) {
            return;
        }
    }

    return;
}

From source file:org.finra.dm.dao.impl.DmDaoImpl.java

/**
 * {@inheritDoc}//from  ww  w  .j av a2 s. c o m
 */
@Override
@Cacheable(DaoSpringModuleConfig.DM_CACHE_NAME)
public List<String> getSecurityFunctionsForRole(String roleCd) {
    // Create the criteria builder and a tuple style criteria query.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    // CriteriaQuery<Tuple> criteria = builder.createTupleQuery();
    CriteriaQuery<String> criteria = builder.createQuery(String.class);

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

    // Join to the other tables we can filter on.
    Join<SecurityRoleFunctionEntity, SecurityRoleEntity> securityRoleEntity = securityRoleFunctionEntity
            .join(SecurityRoleFunctionEntity_.securityRole);
    Join<SecurityRoleFunctionEntity, SecurityFunctionEntity> securityFunctionEntity = securityRoleFunctionEntity
            .join(SecurityRoleFunctionEntity_.securityFunction);

    // Get the columns.
    Path<String> functionCodeColumn = securityFunctionEntity.get(SecurityFunctionEntity_.code);

    // Add the select clause.
    criteria.select(functionCodeColumn);

    criteria.where(builder.equal(builder.upper(securityRoleEntity.get(SecurityRoleEntity_.code)),
            roleCd.toUpperCase()));

    // Add the order by clause.
    criteria.orderBy(builder.asc(functionCodeColumn));

    // Run the query to get a list of tuples back.
    return entityManager.createQuery(criteria).getResultList();
}

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

private void addPredicateToken(String theParamName, List<? extends IQueryParameterType> theList) {

    if (Boolean.TRUE.equals(theList.get(0).getMissing())) {
        addPredicateParamMissing("myParamsToken", theParamName, ResourceIndexedSearchParamToken.class);
        return;/*w  w  w .  ja  v a  2s.  c o  m*/
    }

    CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
    CriteriaQuery<Long> cq = builder.createQuery(Long.class);
    Root<ResourceIndexedSearchParamToken> from = cq.from(ResourceIndexedSearchParamToken.class);
    cq.select(from.get("myResourcePid").as(Long.class));

    List<Predicate> codePredicates = new ArrayList<Predicate>();
    for (IQueryParameterType nextOr : theList) {
        if (addPredicateMissingFalseIfPresent(builder, theParamName, from, codePredicates, nextOr)) {
            continue;
        }

        if (nextOr instanceof TokenParam) {
            TokenParam id = (TokenParam) nextOr;
            if (id.isText()) {
                addPredicateString(theParamName, theList);
                continue;
            }
        }

        Predicate singleCode = createPredicateToken(nextOr, theParamName, builder, from);
        if (singleCode == null) {
            doSetPids(new ArrayList<Long>());
            return;
        }
        codePredicates.add(singleCode);
    }

    if (codePredicates.isEmpty()) {
        return;
    }

    List<Predicate> predicates = new ArrayList<Predicate>();
    predicates.add(builder.equal(from.get("myResourceType"), myResourceName));
    predicates.add(builder.equal(from.get("myParamName"), theParamName));
    predicates.add(builder.or(toArray(codePredicates)));
    createPredicateResourceId(builder, cq, predicates, from.get("myResourcePid").as(Long.class));

    cq.where(builder.and(toArray(predicates)));

    TypedQuery<Long> q = myEntityManager.createQuery(cq);
    doSetPids(new HashSet<Long>(q.getResultList()));
}

From source file:net.shopxx.dao.impl.StatisticDaoImpl.java

public List<Statistic> analyze(Statistic.Period period, Date beginDate, Date endDate) {
    Assert.notNull(period);/*  w  w  w  .  j av  a  2 s.c o m*/

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Statistic> criteriaQuery = criteriaBuilder.createQuery(Statistic.class);
    Root<Statistic> root = criteriaQuery.from(Statistic.class);
    switch (period) {
    case year:
        criteriaQuery.select(criteriaBuilder.construct(Statistic.class, root.get("year"),
                criteriaBuilder.sum(root.<Long>get("registerMemberCount")),
                criteriaBuilder.sum(root.<Long>get("createOrderCount")),
                criteriaBuilder.sum(root.<Long>get("completeOrderCount")),
                criteriaBuilder.sum(root.<BigDecimal>get("createOrderAmount")),
                criteriaBuilder.sum(root.<BigDecimal>get("completeOrderAmount"))));
        criteriaQuery.groupBy(root.get("year"));
        break;
    case month:
        criteriaQuery.select(criteriaBuilder.construct(Statistic.class, root.get("year"), root.get("month"),
                criteriaBuilder.sum(root.<Long>get("registerMemberCount")),
                criteriaBuilder.sum(root.<Long>get("createOrderCount")),
                criteriaBuilder.sum(root.<Long>get("completeOrderCount")),
                criteriaBuilder.sum(root.<BigDecimal>get("createOrderAmount")),
                criteriaBuilder.sum(root.<BigDecimal>get("completeOrderAmount"))));
        criteriaQuery.groupBy(root.get("year"), root.get("month"));
        break;
    case day:
        criteriaQuery.select(criteriaBuilder.construct(Statistic.class, root.get("year"), root.get("month"),
                root.get("day"), root.<Long>get("registerMemberCount"), root.<Long>get("createOrderCount"),
                root.<Long>get("completeOrderCount"), root.<BigDecimal>get("createOrderAmount"),
                root.<BigDecimal>get("completeOrderAmount")));
        break;
    }
    Predicate restrictions = criteriaBuilder.conjunction();
    if (beginDate != null) {
        Calendar calendar = DateUtils.toCalendar(beginDate);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.or(criteriaBuilder.greaterThan(root.<Integer>get("year"), year),
                        criteriaBuilder.and(criteriaBuilder.equal(root.<Integer>get("year"), year),
                                criteriaBuilder.greaterThan(root.<Integer>get("month"), month)),
                        criteriaBuilder.and(criteriaBuilder.equal(root.<Integer>get("year"), year),
                                criteriaBuilder.equal(root.<Integer>get("month"), month),
                                criteriaBuilder.greaterThanOrEqualTo(root.<Integer>get("day"), day))));
    }
    if (endDate != null) {
        Calendar calendar = DateUtils.toCalendar(endDate);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.or(criteriaBuilder.lessThan(root.<Integer>get("year"), year),
                        criteriaBuilder.and(criteriaBuilder.equal(root.<Integer>get("year"), year),
                                criteriaBuilder.lessThan(root.<Integer>get("month"), month)),
                        criteriaBuilder.and(criteriaBuilder.equal(root.<Integer>get("year"), year),
                                criteriaBuilder.equal(root.<Integer>get("month"), month),
                                criteriaBuilder.lessThanOrEqualTo(root.<Integer>get("day"), day))));
    }
    criteriaQuery.where(restrictions);
    return entityManager.createQuery(criteriaQuery).getResultList();
}

From source file:utils.jpa.EntityResource.java

private Query createCommonQuery(CriteriaBuilder cb, CriteriaQuery cq, Root root, TableSearchQuery tb,
        List<String> fieldsSearchBy) {

    List<Predicate> orPredicates = new ArrayList<>();
    List<Predicate> andPredicates = new ArrayList<>();

    //setting where conditions      
    if (fieldsSearchBy != null && !fieldsSearchBy.isEmpty()) {
        for (String field : fieldsSearchBy) {
            if (tb.getFilter() != null && !tb.getFilter().isEmpty()) {
                orPredicates.add(cb.like(cb.lower(cb.concat(root.<String>get(field), "::text")),
                        "%" + tb.getFilter().toLowerCase() + "%"));
            }/*from  w w w  .  j  a v a  2s.  co m*/
        }
    } else {
        List<Field> filterColumns = SearchFields.getAll(entityClass);
        for (Field field : filterColumns) {
            EntityFilter entityFilter = tb.getFilterParameters().get(field.getName());

            if ((Collection.class.isAssignableFrom(field.getType())
                    || List.class.isAssignableFrom(field.getType()))
                    && (entityFilter == null
                            || !entityFilter.getEntityFilterType().equals(EntityFilterType.EMPTY))) {
                continue;
            }

            if (entityFilter == null) {
                if (tb.getFilter() != null && !tb.getFilter().isEmpty()) {
                    orPredicates.add(cb.like(cb.lower(cb.concat(root.<String>get(field.getName()), "::text")),
                            "%" + tb.getFilter().toLowerCase() + "%"));
                }
                continue;
            }

            switch (entityFilter.getEntityFilterType()) {
            case WILDCARD:
                andPredicates.add(cb.like(cb.lower(cb.concat(root.<String>get(field.getName()), "::text")),
                        "%" + entityFilter.getValue().toLowerCase() + "%"));
                break;
            case EMPTY:
                if (Collection.class.isAssignableFrom(field.getType())
                        || List.class.isAssignableFrom(field.getType())) {
                    andPredicates.add(entityFilter.getValue().equals("hide")
                            ? cb.isEmpty(root.<Collection>get(field.getName()))
                            : cb.isNotEmpty(root.<Collection>get(field.getName())));
                } else {
                    andPredicates.add(
                            entityFilter.getValue().equals("hide") ? root.<Object>get(field.getName()).isNull()
                                    : root.<Object>get(field.getName()).isNotNull());
                }

                break;
            case MIN_MAX:
                andPredicates.add(cb.greaterThanOrEqualTo(root.<Date>get(field.getName()),
                        new Date(Long.valueOf(entityFilter.getValues().get(0)))));
                andPredicates.add(cb.lessThanOrEqualTo(root.<Date>get(field.getName()),
                        new Date(Long.valueOf(entityFilter.getValues().get(1)))));
                break;
            case MIN:
                andPredicates.add(cb.greaterThanOrEqualTo(root.<Date>get(field.getName()),
                        new Date(Long.valueOf(entityFilter.getValue()))));
                break;
            case MAX:
                andPredicates.add(cb.lessThanOrEqualTo(root.<Date>get(field.getName()),
                        new Date(Long.valueOf(entityFilter.getValue()))));
                break;
            }

        }
    }
    if (orPredicates.size() > 0 && andPredicates.size() > 0) {
        cq.where(cb.or(cb.or(orPredicates.toArray(new Predicate[0])),
                cb.and(andPredicates.toArray(new Predicate[0]))));
    } else if (orPredicates.size() > 0) {
        cq.where(cb.or(orPredicates.toArray(new Predicate[0])));
    } else if (andPredicates.size() > 0) {
        cq.where(cb.and(andPredicates.toArray(new Predicate[0])));
    }

    return em.createQuery(cq);

}

From source file:org.finra.dm.dao.impl.DmDaoImpl.java

/**
 * {@inheritDoc}// w  w  w. j  av a  2 s .c  om
 */
@Override
public List<BusinessObjectDefinitionKey> getBusinessObjectDefinitions(String namespaceCode) {
    // Create the criteria builder and a tuple style criteria query.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteria = builder.createTupleQuery();

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

    // Join to the other tables we can filter on.
    Join<BusinessObjectDefinitionEntity, NamespaceEntity> namespaceEntity = businessObjectDefinitionEntity
            .join(BusinessObjectDefinitionEntity_.namespace);

    // Get the columns.
    Path<String> namespaceCodeColumn = namespaceEntity.get(NamespaceEntity_.code);
    Path<String> businessObjectDefinitionNameColumn = businessObjectDefinitionEntity
            .get(BusinessObjectDefinitionEntity_.name);

    // Add the select clause.
    criteria.multiselect(namespaceCodeColumn, businessObjectDefinitionNameColumn);

    // If namespace code is specified, add the where clause.
    if (StringUtils.isNotBlank(namespaceCode)) {
        criteria.where(builder.equal(builder.upper(namespaceEntity.get(NamespaceEntity_.code)),
                namespaceCode.toUpperCase()));
    }

    // Add the order by clause.
    if (StringUtils.isNotBlank(namespaceCode)) {
        criteria.orderBy(builder.asc(namespaceCodeColumn), builder.asc(businessObjectDefinitionNameColumn));
    } else {
        criteria.orderBy(builder.asc(businessObjectDefinitionNameColumn));
    }

    // Run the query to get a list of tuples back.
    List<Tuple> tuples = entityManager.createQuery(criteria).getResultList();

    // Populate the "keys" objects from the returned tuples (i.e. 1 tuple for each row).
    List<BusinessObjectDefinitionKey> businessObjectDefinitionKeys = new ArrayList<>();
    for (Tuple tuple : tuples) {
        BusinessObjectDefinitionKey businessObjectDefinitionKey = new BusinessObjectDefinitionKey();
        businessObjectDefinitionKeys.add(businessObjectDefinitionKey);
        businessObjectDefinitionKey.setNamespace(tuple.get(namespaceCodeColumn));
        businessObjectDefinitionKey
                .setBusinessObjectDefinitionName(tuple.get(businessObjectDefinitionNameColumn));
    }

    return businessObjectDefinitionKeys;
}