Example usage for javax.persistence.criteria CriteriaBuilder between

List of usage examples for javax.persistence.criteria CriteriaBuilder between

Introduction

In this page you can find the example usage for javax.persistence.criteria CriteriaBuilder between.

Prototype

<Y extends Comparable<? super Y>> Predicate between(Expression<? extends Y> v, Y x, Y y);

Source Link

Document

Create a predicate for testing whether the first argument is between the second and third arguments in value.

Usage

From source file:com.bxf.hradmin.common.utils.QueryParameterTransformer.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static Predicate generatePredicate(Root root, CriteriaBuilder builder,
        QueryParameter... queryParameters) {
    Predicate condition = builder.conjunction();
    for (QueryParameter queryParameter : queryParameters) {
        Object value = queryParameter.getValue();
        if (value == null || StringUtils.isBlank(value.toString())) {
            continue;
        }/*from ww w  .j a v  a 2  s  .c  om*/
        Path path = root.get(queryParameter.getKey());
        switch (queryParameter.getMode()) {
        case BETWEEN:
            Object[] values = asArray(value);
            if (values != null) {
                condition = builder.and(builder.between((Path<Comparable>) path, asComparable(values[0]),
                        asComparable(values[1])));
            }
            break;
        case GREATER_THAN:
            condition = builder.and(condition,
                    builder.greaterThan((Path<Comparable>) path, asComparable(value)));
            break;
        case GREATER_EQUALS:
            condition = builder.and(condition,
                    builder.greaterThanOrEqualTo((Path<Comparable>) path, asComparable(value)));
            break;
        case LESS_THAN:
            condition = builder.and(condition, builder.lessThan((Path<Comparable>) path, asComparable(value)));
            break;
        case LESS_EQUALS:
            condition = builder.and(condition,
                    builder.lessThanOrEqualTo((Path<Comparable>) path, asComparable(value)));
            break;
        case IS_NULL:
            condition = builder.and(condition, builder.isNull(path));
            break;
        case IS_NOT_NULL:
            condition = builder.and(condition, builder.isNotNull(path));
            break;
        case IN:
            condition = builder.and(condition, path.in(asArray(value)));
            break;
        case NOT_IN:
            condition = builder.and(condition, builder.not(path.in(asArray(value))));
            break;
        case LIKE:
            condition = builder.and(condition, builder.like(path, "%" + String.valueOf(value) + "%"));
            break;
        case NOT_LIKE:
            condition = builder.and(condition, builder.notLike(path, "%" + String.valueOf(value) + "%"));
            break;
        case EQUALS:
            condition = builder.and(condition, builder.equal(path, value));
            break;
        case NOT_EQUALS:
            condition = builder.and(condition, builder.notEqual(path, value));
            break;
        default:
            break;
        }
    }
    return condition;
}

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

/**
 * Creates a JPA2 predicate based on a Filter
 * /*from  w w w . j ava  2s. com*/
 * @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:com.fantasy.stataggregator.workers.GameDataRetrieverTask.java

/**
 * Sets the statistical year to be requested.
 *
 * @param year// w ww. ja  v  a  2s . c  o  m
 * @throws java.text.ParseException
 */
@Override
public void setYear(int year) throws ParseException {
    if (Objects.nonNull(ctx)) {
        this.year = year;
        isTaskComplete = false;
        GameScheduleRepository gsr = ctx.getBean(GameScheduleRepository.class);
        if (year == Integer.MAX_VALUE) {
            schedules = gsr.findAll();
        } else {
            SimpleDateFormat sdf = ctx.getBean(SimpleDateFormat.class);
            sdf.applyLocalizedPattern("yyyyMMdd");

            Date min = sdf.parse(year + START_OF_YEAR);
            Date max = sdf.parse(year + END_OF_YEAR);

            CriteriaBuilder cb = gsr.getCriteriaBuilder();
            CriteriaQuery<GameSchedule> cq = gsr.getCriteriaQuery();
            Root<GameSchedule> gameSchedule = gsr.getRoot();
            cq.select(gameSchedule).where(cb.between(gameSchedule.get(GameSchedule_.gamedate), min, max))
                    .orderBy(cb.asc(gameSchedule.get(GameSchedule_.gameid)));

            schedules = gsr.getCriteriaList(cq);
            System.out.println(schedules.size());
        }
    }
}

From source file:com.qpark.eip.core.spring.statistics.dao.StatisticsLoggingDao.java

/**
 * Get all {@link SystemUserLogType}s of the day of the application.
 *
 * @param date//from  w  ww  .java  2s. c om
 *            the date the calls are recorded.
 * @return the list of {@link SystemUserLogType}s.
 */
@Transactional(value = EipPersistenceConfig.TRANSACTION_MANAGER_NAME, propagation = Propagation.REQUIRED)
public List<SystemUserLogType> getSystemUserLogType(final Date date) {
    final CriteriaBuilder cb = this.em.getCriteriaBuilder();
    Date d = date;
    if (d == null) {
        d = new Date();
    }
    final CriteriaQuery<SystemUserLogType> q = cb.createQuery(SystemUserLogType.class);
    final Root<SystemUserLogType> c = q.from(SystemUserLogType.class);
    q.where(cb.equal(c.<String>get(SystemUserLogType_.context), this.contextNameProvider.getContextName()),
            cb.between(c.<Date>get(SystemUserLogType_.logDateItem), getDayStart(d), getDayEnd(d)));

    final TypedQuery<SystemUserLogType> typedQuery = this.em.createQuery(q);
    return typedQuery.getResultList();
}

From source file:com.qpark.eip.core.spring.statistics.dao.StatisticsLoggingDao.java

/**
 * Get all {@link ApplicationUserLogType}s of the day of the application.
 *
 * @param date//from  w w  w  .j  a v a  2 s.  com
 *            the date the calls are recorded.
 * @return the list of {@link SystemUserLogType}s.
 */
@Transactional(value = EipPersistenceConfig.TRANSACTION_MANAGER_NAME, propagation = Propagation.REQUIRED)
public List<ApplicationUserLogType> getApplicationUserLogType(final Date date) {
    final CriteriaBuilder cb = this.em.getCriteriaBuilder();
    Date d = date;
    if (d == null) {
        d = new Date();
    }
    final CriteriaQuery<ApplicationUserLogType> q = cb.createQuery(ApplicationUserLogType.class);
    final Root<ApplicationUserLogType> c = q.from(ApplicationUserLogType.class);
    q.where(cb.equal(c.<String>get(ApplicationUserLogType_.context), this.contextNameProvider.getContextName()),
            cb.between(c.<Date>get(ApplicationUserLogType_.startItem), getDayStart(d), getDayEnd(d)));

    final TypedQuery<ApplicationUserLogType> typedQuery = this.em.createQuery(q);
    return typedQuery.getResultList();
}

From source file:edu.umm.radonc.ca_dash.model.TxInstanceFacade.java

public List<TxInstance> itemsDateRange(Date startDate, Date endDate, int[] range) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery(TxInstance.class);
    Root<TxInstance> rt = cq.from(TxInstance.class);
    cq.where(cb.and(rt.get(TxInstance_.completed).isNotNull(),
            cb.between(rt.get(TxInstance_.completed), startDate, endDate)));
    cq.orderBy(cb.asc(rt.get(TxInstance_.completed)));
    Query q = em.createQuery(cq);
    q.setMaxResults(range[1] - range[0] + 1);
    q.setFirstResult(range[0]);//from  ww  w  .j a v a 2  s.  co m
    return q.getResultList();
}

From source file:com.hengyi.japp.execution.Util.java

public static void queryCommand(CriteriaBuilder cb, CriteriaQuery<?> cq, Root<Task> root,
        TaskQueryCommand command) {//from  w w w. ja  v  a2s .  c o m
    Predicate p1 = cb.equal(root.get(Task_.charger), command.getOperator());
    ListJoin<Task, Operator> joinFollowers = root.join(Task_.followers, JoinType.LEFT);
    Predicate p2 = cb.equal(joinFollowers.get(Operator_.id), command.getOperator().getId());
    ListJoin<Task, Operator> joinExecutors = root.join(Task_.executors, JoinType.LEFT);
    Predicate p3 = cb.equal(joinExecutors.get(Operator_.id), command.getOperator().getId());
    Predicate p = cb.or(p1, p2, p3);
    if (command.getExecutor() != null) {
        p = cb.and(p, cb.equal(p, cb.isMember(command.getExecutor(), root.get(Task_.executors))));
    }
    if (command.getCustomer() != null) {
        p = cb.and(p, cb.equal(root.get(Task_.customer), command.getCustomer()));
    }
    if (!isBlank(command.getContent())) {
        p = cb.and(p, cb.like(root.get(Task_.content), command.getContentQuery()));
    }
    Collection<TaskType> TaskTypes = command.getTypes();
    if (TaskTypes != null && !TaskTypes.isEmpty()) {
        p = cb.and(p, root.get(Task_.type).in(TaskTypes));
    }
    Collection<TaskStatus> statuses = command.getStatuses();
    if (statuses != null && !statuses.isEmpty()) {
        p = cb.and(p, root.get(Task_.status).in(statuses));
    }
    if (command.getCreateDate() != null) {
        Date createDateStart = LocalDate.fromDateFields(command.getCreateDate()).toDate();
        Date createDateEnd = LocalDate.fromDateFields(command.getCreateDate()).plusDays(1).toDate();
        p = cb.and(p, cb.between(root.get(Task_.logInfo).get(LogInfo_.createDateTime), createDateStart,
                createDateEnd));
        // TODO timestamp date convert
        //p = cb.and(p, cb.equal(root.get(Task_.logInfo).get(LogInfo_.createDateTime).as(java.sql.Date.class), command.getCreateDate()));
    }
    cq.where(p);
}

From source file:edu.umm.radonc.ca_dash.model.TxInstanceFacade.java

public int itemsDateRangeCount(Date startDate, Date endDate) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery(TxInstance.class);
    Root<TxInstance> rt = cq.from(TxInstance.class);
    cq.select(cb.count(rt.get(TxInstance_.activityinstanceser)));
    cq.where(cb.and(rt.get(TxInstance_.completed).isNotNull(),
            cb.between(rt.get(TxInstance_.completed), startDate, endDate)));

    Query q = em.createQuery(cq);
    return ((Long) (q.getSingleResult())).intValue();
}

From source file:edu.umm.radonc.ca_dash.model.ActivityFacade.java

public List<ActivityAIPC> itemsDateRange(Date start, Date end, int[] range) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery(ActivityAIPC.class);
    Root<ActivityAIPC> rt = cq.from(ActivityAIPC.class);
    cq.where(cb.and(rt.get(ActivityAIPC_.fromdateofservice).isNotNull(),
            cb.and(cb.notEqual(rt.get(ActivityAIPC_.procedurecodeser), 528),
                    cb.notEqual(rt.get(ActivityAIPC_.procedurecodeser), 529),
                    cb.notEqual(rt.get(ActivityAIPC_.procedurecodeser), 530),
                    cb.between(rt.get(ActivityAIPC_.fromdateofservice), start, end))));
    cq.orderBy(cb.asc(rt.get(ActivityAIPC_.fromdateofservice)));
    Query q = em.createQuery(cq);
    q.setMaxResults(range[1] - range[0] + 1);
    q.setFirstResult(range[0]);/*from   www.j  a v  a2s. c o  m*/
    return q.getResultList();

}

From source file:eu.uqasar.service.dataadapter.JiraDataService.java

/**
 * //ww w  .  ja v  a 2s . c  o  m
 * @param metric
 * @return
 * @throws uQasarException
 */
public int countMeasurementsPerProjectByMetricWithinPeriod(Project project, String metric, String period)
        throws uQasarException {
    logger.info("Count measurements for metric: " + metric);

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<JiraMetricMeasurement> query = cb.createQuery(JiraMetricMeasurement.class);
    Root<JiraMetricMeasurement> root = query.from(JiraMetricMeasurement.class);
    Predicate condition1 = cb.equal(root.get(JiraMetricMeasurement_.jiraMetric), metric);
    Predicate condition2 = cb.equal(root.get(JiraMetricMeasurement_.project), project);

    Date from = getDateForPeriod(period);
    Date to = DateTime.now().toDate();
    Predicate condition3 = cb.between(root.get(JiraMetricMeasurement_.timeStamp), from, to);
    Predicate condition4 = cb.and(condition1, condition2, condition3);
    query.where(condition4);
    query.orderBy(cb.desc(root.get(JiraMetricMeasurement_.timeStamp)));
    Integer res = em.createQuery(query).getResultList().size();
    logger.info("Results' count: " + res);
    return res;
}