Example usage for org.hibernate.criterion Restrictions lt

List of usage examples for org.hibernate.criterion Restrictions lt

Introduction

In this page you can find the example usage for org.hibernate.criterion Restrictions lt.

Prototype

public static SimpleExpression lt(String propertyName, Object value) 

Source Link

Document

Apply a "less than" constraint to the named property

Usage

From source file:org.ikasan.wiretap.dao.HibernateWiretapDao.java

License:BSD License

/**
 * Identifies a batch (List of Ids) of housekeepable items
 * /*  w ww  .j av  a2  s  .co  m*/
 * @return List of ids for WiretapFlowEvents
 */
@SuppressWarnings("unchecked")
private List<Long> getHousekeepableBatch() {
    return (List<Long>) getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException {
            List<Long> ids = new ArrayList<Long>();

            Criteria criteria = session.createCriteria(WiretapEvent.class);
            criteria.add(Restrictions.lt("expiry", System.currentTimeMillis()));
            criteria.setMaxResults(housekeepingBatchSize);

            for (Object wiretapFlowEventObj : criteria.list()) {
                WiretapEvent wiretapFlowEvent = (WiretapEvent) wiretapFlowEventObj;
                ids.add(wiretapFlowEvent.getIdentifier());
            }

            return ids;

        }
    });
}

From source file:org.ikasan.wiretap.dao.HibernateWiretapDao.java

License:BSD License

/**
 * Checks if there are housekeepable items in existance, ie expired WiretapFlowEvents
 * // w w w  .ja v a2 s .  c  o m
 * @return true if there is at least 1 expired WiretapFlowEvent 
 */
private boolean housekeepablesExist() {
    return (Boolean) getHibernateTemplate().execute(new HibernateCallback<Object>() {
        public Object doInHibernate(Session session) throws HibernateException {
            Criteria criteria = session.createCriteria(WiretapEvent.class);
            criteria.add(Restrictions.lt("expiry", System.currentTimeMillis()));
            criteria.setProjection(Projections.rowCount());
            Long rowCount = new Long(0);
            List<Long> rowCountList = criteria.list();
            if (!rowCountList.isEmpty()) {
                rowCount = rowCountList.get(0);
            }
            logger.info(rowCount + ", housekeepables exist");
            return new Boolean(rowCount > 0);

        }
    });
}

From source file:org.infoscoop.dao.SessionDAO.java

License:Open Source License

/**
 * Return the session counting in the designated days.
 * @param period//w ww.j  ava  2s .c o m
 * @return
 */
public int getActiveSessionsCount(final int period) {
    return (Integer) super.getHibernateTemplate().execute(new HibernateCallback() {

        public Object doInHibernate(org.hibernate.Session session) throws HibernateException, SQLException {

            Criteria crit = session.createCriteria(Session.class);

            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DATE, period);

            Date startDate = cal.getTime();
            Date endDate = new Date();

            crit.add(Restrictions.gt("Logindatetime", startDate));
            crit.add(Restrictions.lt("Logindatetime", endDate));
            Integer rowCount = (Integer) crit.setProjection(Projections.rowCount()).uniqueResult();

            return rowCount;
        }

    });
}

From source file:org.iternine.jeppetto.dao.hibernate.HibernateQueryModelDAO.java

License:Apache License

@Override
public Condition buildCondition(String conditionField, ConditionType conditionType, Iterator argsIterator) {
    Condition condition = new Condition();

    condition.setField(conditionField);/*  www . j a  va  2  s. co  m*/

    switch (conditionType) {
    case Between:
        condition.setConstraint(Restrictions.between(conditionField, argsIterator.next(), argsIterator.next()));
        break;

    case Equal:
        condition.setConstraint(Restrictions.eq(conditionField, argsIterator.next()));
        break;

    case GreaterThan:
        condition.setConstraint(Restrictions.gt(conditionField, argsIterator.next()));
        break;

    case GreaterThanEqual:
        condition.setConstraint(Restrictions.ge(conditionField, argsIterator.next()));
        break;

    case IsNotNull:
        condition.setConstraint(Restrictions.isNotNull(conditionField));
        break;

    case IsNull:
        condition.setConstraint(Restrictions.isNull(conditionField));
        break;

    case LessThan:
        condition.setConstraint(Restrictions.lt(conditionField, argsIterator.next()));
        break;

    case LessThanEqual:
        condition.setConstraint(Restrictions.le(conditionField, argsIterator.next()));
        break;

    case NotEqual:
        condition.setConstraint(Restrictions.ne(conditionField, argsIterator.next()));
        break;

    case NotWithin:
        condition.setConstraint(
                Restrictions.not(Restrictions.in(conditionField, (Collection) argsIterator.next())));
        break;

    case Within:
        condition.setConstraint(Restrictions.in(conditionField, (Collection) argsIterator.next()));
        break;
    }

    return condition;
}

From source file:org.jasig.ssp.dao.MessageDao.java

License:Apache License

public PagingWrapper<Message> queued(SortingAndPaging sAndP) {
    int retryConfig = configService.getByNameExceptionOrDefaultAsInt("mail_delivery_retry_limit");
    // will let the caller decide on object status filtering, but since
    // this method is supposed to act like a queue, at least make sure
    // it acts that way by default.
    if (!(sAndP.isSorted()) && !(sAndP.isDefaultSorted())) {
        sAndP.appendSortField("createdDate", SortDirection.ASC);
    }//from   w  w  w .  j  a v a 2  s  . c om
    // cannot use createCriteria(sAndP) b/c that applies the sort order
    // immediately, which breaks the 'select count()' that runs as part
    // of the query pagination mechanism. The sort order will be applied
    // to the criteria as part of processCriteriaWithSortingAndPaging()
    // below.
    Criteria criteria = this.createCriteria();
    criteria.add(Restrictions.isNull("sentDate"));
    criteria.add(
            Restrictions.or(Restrictions.isNull("retryCount"), Restrictions.lt("retryCount", retryConfig)));
    return processCriteriaWithStatusSortingAndPaging(criteria, sAndP);
}

From source file:org.jasig.ssp.dao.PlanDao.java

License:Apache License

@SuppressWarnings("unchecked")
public List<PlanAdvisorCountTO> getPlanCountByOwner(SearchPlanTO form) {
    Criteria criteria = createCriteria();

    if (form.getDateFrom() != null)
        criteria.add(Restrictions.ge("modifiedDate", form.getDateFrom()));
    if (form.getDateTo() != null)
        criteria.add(Restrictions.lt("modifiedDate", form.getDateTo()));

    criteria.add(Restrictions.eq("objectStatus", ObjectStatus.ACTIVE));

    criteria.createAlias("owner", "owner");
    criteria.setProjection(/*from  w w  w.j a va 2  s . c o m*/
            Projections.projectionList().add(Projections.countDistinct("id").as("plan_entityCount")).
            // cannot just group by owner, else you get a N+1
            // http://stackoverflow.com/questions/4330480/prevent-hibernate-n1-selects-when-grouping-by-an-entity
            // (plus EntityStudentCountByCoachTO doesn't map Persons, just AuditPersons)
                    add(Projections.groupProperty("owner.id").as("plan_coachId"))
                    .add(Projections.groupProperty("owner.firstName").as("plan_coachFirstName"))
                    .add(Projections.groupProperty("owner.lastName").as("plan_coachLastName")));

    List<EntityStudentCountByCoachTO> activePlansByCoaches = criteria
            .setResultTransformer(
                    new NamespacedAliasToBeanResultTransformer(EntityStudentCountByCoachTO.class, "plan_"))
            .list();

    criteria = createCriteria();

    if (form.getDateFrom() != null)
        criteria.add(Restrictions.ge("modifiedDate", form.getDateFrom()));
    if (form.getDateTo() != null)
        criteria.add(Restrictions.lt("modifiedDate", form.getDateTo()));

    criteria.add(Restrictions.eq("objectStatus", ObjectStatus.INACTIVE));

    criteria.createAlias("owner", "owner");
    criteria.setProjection(
            Projections.projectionList().add(Projections.countDistinct("id").as("plan_entityCount")).
            // cannot just group by owner, else you get a N+1
            // http://stackoverflow.com/questions/4330480/prevent-hibernate-n1-selects-when-grouping-by-an-entity
            // (plus EntityStudentCountByCoachTO doesn't map Persons, just AuditPersons)
                    add(Projections.groupProperty("owner.id").as("plan_coachId"))
                    .add(Projections.groupProperty("owner.firstName").as("plan_coachFirstName"))
                    .add(Projections.groupProperty("owner.lastName").as("plan_coachLastName")));

    List<EntityStudentCountByCoachTO> inactivePlansByCoaches = criteria
            .setResultTransformer(
                    new NamespacedAliasToBeanResultTransformer(EntityStudentCountByCoachTO.class, "plan_"))
            .list();

    Map<UUID, PlanAdvisorCountTO> results = new HashMap<UUID, PlanAdvisorCountTO>();
    for (EntityStudentCountByCoachTO inactivePlan : inactivePlansByCoaches) {
        if (results.containsKey(inactivePlan.getCoach().getId())) {
            PlanAdvisorCountTO result = results.get(inactivePlan.getCoach().getId());
            result.setInactivePlanCount(inactivePlan.getEntityCount());
        } else {
            PlanAdvisorCountTO result = new PlanAdvisorCountTO();
            result.setCoachName(
                    inactivePlan.getCoach().getFirstName() + " " + inactivePlan.getCoach().getLastName());
            result.setInactivePlanCount(inactivePlan.getEntityCount());
            results.put(inactivePlan.getCoach().getId(), result);
        }
    }

    for (EntityStudentCountByCoachTO activePlan : activePlansByCoaches) {
        if (results.containsKey(activePlan.getCoach().getId())) {
            PlanAdvisorCountTO result = results.get(activePlan.getCoach().getId());
            result.setActivePlanCount(activePlan.getEntityCount());
        } else {
            PlanAdvisorCountTO result = new PlanAdvisorCountTO();
            result.setCoachName(
                    activePlan.getCoach().getFirstName() + " " + activePlan.getCoach().getLastName());
            result.setActivePlanCount(activePlan.getEntityCount());
            results.put(activePlan.getCoach().getId(), result);
        }
    }
    List<PlanAdvisorCountTO> sortedResults = Lists.newArrayList(results.values());
    Collections.sort(sortedResults, PlanAdvisorCountTO.COACH_NAME_COMPARATOR);
    return sortedResults;
}

From source file:org.jpos.ee.pm.core.DBEntityFilter.java

License:Open Source License

protected Criterion getCompareCriterion(String fid, List<Object> values) {
    Object value_0 = values.get(0);
    switch (getFilterOperation(fid)) {
    case LIKE://  w ww. ja va2s .  c o m
        if (value_0 instanceof String) {
            return Restrictions.ilike(fid, "%" + value_0 + "%");
        } else {
            return Restrictions.eq(fid, value_0);
        }
    case GE:
        return Restrictions.ge(fid, value_0);
    case GT:
        return Restrictions.gt(fid, value_0);
    case LE:
        return Restrictions.le(fid, value_0);
    case LT:
        return Restrictions.lt(fid, value_0);
    case NE:
        return Restrictions.not(Restrictions.eq(fid, value_0));
    default:
        return Restrictions.eq(fid, value_0);
    }
}

From source file:org.jpos.gl.GLSession.java

License:Open Source License

/**
 * Get Both Balances at given date//w  w w.j  ava 2 s  .c om
 * @param journal the journal.
 * @param acct the account.
 * @param date date (inclusive).
 * @param inclusive either true or false
 * @param layers the layers
 * @param maxId maximum GLEntry ID to be considered in the query (if greater than zero)
 * @return array of 2 BigDecimals with balance and entry count.
 * @throws GLException if user doesn't have READ permission on this jounral.
 */
public BigDecimal[] getBalances(Journal journal, Account acct, Date date, boolean inclusive, short[] layers,
        long maxId) throws HibernateException, GLException {
    checkPermission(GLPermission.READ, journal);
    BigDecimal balance[] = { ZERO, Z };
    if (acct.getChildren() != null) {
        if (acct.isChart()) {
            return getChartBalances(journal, (CompositeAccount) acct, date, inclusive, layers, maxId);
        }
        Iterator iter = acct.getChildren().iterator();
        while (iter.hasNext()) {
            Account a = (Account) iter.next();
            BigDecimal[] b = getBalances(journal, a, date, inclusive, layers, maxId);
            balance[0] = balance[0].add(b[0]);
            // session.evict (a); FIXME this conflicts with r251 (cascade=evict genearting a failed to lazily initialize a collection
        }
    } else if (acct.isFinalAccount()) {
        Criteria entryCrit = session.createCriteria(GLEntry.class).add(Restrictions.eq("account", acct))
                .add(Restrictions.in("layer", toShortArray(layers)));
        if (maxId > 0L)
            entryCrit.add(Restrictions.le("id", maxId));

        Criteria txnCrit = entryCrit.createCriteria("transaction").add(Restrictions.eq("journal", journal));
        if (date != null) {
            if (inclusive) {
                txnCrit.add(Restrictions.lt("postDate", Util.tomorrow(date)));
            } else {
                date = Util.floor(date);
                txnCrit.add(Restrictions.lt("postDate", date));
            }
            Checkpoint chkp = getRecentCheckpoint(journal, acct, date, inclusive, layers);
            if (chkp != null) {
                balance[0] = chkp.getBalance();
                txnCrit.add(Restrictions.gt("postDate", chkp.getDate()));
            }

        } else {
            BalanceCache bcache = getBalanceCache(journal, acct, layers);
            if (bcache != null) {
                balance[0] = bcache.getBalance();
                entryCrit.add(Restrictions.gt("id", bcache.getRef()));
            }
        }
        List l = txnCrit.list();
        balance[0] = applyEntries(balance[0], l);
        balance[1] = new BigDecimal(l.size()); // hint for checkpoint
    }
    return balance;
}

From source file:org.jpos.gl.GLSession.java

License:Open Source License

/**
 * @param journal the journal.//from  w  w w . jav  a2 s  .c o  m
 * @param acct the account.
 * @param date date (null for last checkpoint)
 * @param inclusive either true or false
 * @return Most recent check point for given date.
 * @throws GLException if user doesn't have CHECKPOINT permission on this jounral.
 */
public Checkpoint getRecentCheckpoint(Journal journal, Account acct, Date date, boolean inclusive,
        short[] layers) throws HibernateException, GLException {
    checkPermission(GLPermission.CHECKPOINT, journal);

    Criteria crit = session.createCriteria(Checkpoint.class).add(Restrictions.eq("journal", journal))
            .add(Restrictions.eq("account", acct));

    if (layers != null)
        crit.add(Restrictions.eq("layers", layersToString(layers)));

    if (date != null) {
        if (inclusive)
            crit.add(Restrictions.le("date", date));
        else
            crit.add(Restrictions.lt("date", date));
    }
    crit.addOrder(Order.desc("date"));
    crit.setMaxResults(1);
    return (Checkpoint) crit.uniqueResult();
}

From source file:org.jspresso.framework.model.persistence.hibernate.criterion.DefaultCriteriaFactory.java

License:Open Source License

/**
 * Creates a criterion by processing a comparable query structure.
 *
 * @param path//from w w w  . ja  v a  2s .  co m
 *     the path to the comparable property.
 * @param queryStructure
 *     the comparable query structure.
 * @param componentDescriptor
 *     the component descriptor
 * @param queryComponent
 *     the query component
 * @param context
 *     the context
 * @return the created criterion or null if no criterion necessary.
 */
protected Criterion createComparableQueryStructureRestriction(String path,
        ComparableQueryStructure queryStructure, IComponentDescriptor<?> componentDescriptor,
        IQueryComponent queryComponent, Map<String, Object> context) {
    Junction queryStructureRestriction = null;
    if (queryStructure.isRestricting()) {
        queryStructureRestriction = Restrictions.conjunction();
        String comparator = queryStructure.getComparator();
        Object infValue = queryStructure.getInfValue();
        Object supValue = queryStructure.getSupValue();
        Object compareValue = infValue;
        if (compareValue == null) {
            compareValue = supValue;
        }
        switch (comparator) {
        case ComparableQueryStructureDescriptor.EQ:
            queryStructureRestriction.add(Restrictions.eq(path, compareValue));
            break;
        case ComparableQueryStructureDescriptor.GT:
            queryStructureRestriction.add(Restrictions.gt(path, compareValue));
            break;
        case ComparableQueryStructureDescriptor.GE:
            queryStructureRestriction.add(Restrictions.ge(path, compareValue));
            break;
        case ComparableQueryStructureDescriptor.LT:
            queryStructureRestriction.add(Restrictions.lt(path, compareValue));
            break;
        case ComparableQueryStructureDescriptor.LE:
            queryStructureRestriction.add(Restrictions.le(path, compareValue));
            break;
        case ComparableQueryStructureDescriptor.NU:
            queryStructureRestriction.add(Restrictions.isNull(path));
            break;
        case ComparableQueryStructureDescriptor.NN:
            queryStructureRestriction.add(Restrictions.isNotNull(path));
            break;
        case ComparableQueryStructureDescriptor.BE:
            if (infValue != null && supValue != null) {
                queryStructureRestriction.add(Restrictions.between(path, infValue, supValue));
            } else if (infValue != null) {
                queryStructureRestriction.add(Restrictions.ge(path, infValue));
            } else {
                queryStructureRestriction.add(Restrictions.le(path, supValue));
            }
            break;
        default:
            break;
        }
    }
    return queryStructureRestriction;
}