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:edu.ku.brc.specify.dbsupport.customqueries.CustomStatQueries.java

License:Open Source License

protected boolean overdueLoans() {
    //String sql = "select loanId from Loan where (not (currentDueDate is null)) and (IsClosed = false or IsClosed is null) and datediff(CURDATE(), currentduedate) > 0;
    //select count(loanid) as OpenLoanCount from loan where loanid in (select loanid from loan where (not (currentduedate is null)) and loan.IsGift = false and (IsClosed = false or IsClosed is null) and datediff(CURDATE(), currentduedate) > 0)

    Session session = HibernateUtil.getNewSession();

    Calendar today = Calendar.getInstance();

    Criteria criteria = session.createCriteria(Loan.class);
    criteria.add(Restrictions.isNotNull("currentDueDate"));
    criteria.add(Restrictions.lt("currentDueDate", today));
    criteria.add(Restrictions.or(Restrictions.isNull("isClosed"), Restrictions.eq("isClosed", false)));

    Criteria dsp = criteria.createCriteria("discipline");
    dsp.add(Restrictions.eq("disciplineId",
            AppContextMgr.getInstance().getClassObject(Discipline.class).getDisciplineId()));

    criteria.setProjection(Projections.rowCount());
    resultsList = criteria.list();/*from w w w  .  j  a va 2 s . c o m*/

    /*for (Object data : resultsList)
    {
    System.out.println("overdueLoans "+data);
    }*/
    session.close();

    return true;
}

From source file:edu.northwestern.bioinformatics.studycalendar.dao.delta.AmendmentDao.java

License:BSD License

@SuppressWarnings({ "unchecked" })
public Amendment getByNaturalKey(String key, Study study) {
    final Amendment.Key keyParts = Amendment.decomposeNaturalKey(key);
    List<Amendment> results = getHibernateTemplate().executeFind(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException {
            //need to have both "lt & ge" or "eq" criterias to work on Oracle and Postgres dbs for date with timestamp.
            Criteria crit = session.createCriteria(Amendment.class)
                    .add(Restrictions.disjunction()
                            .add(Restrictions.and(Restrictions.lt("date", keyParts.getDateNext()),
                                    Restrictions.ge("date", keyParts.getDate())))
                            .add(Restrictions.eq("date", keyParts.getDate())));
            if (keyParts.getName() != null)
                crit.add(Restrictions.eq("name", keyParts.getName()));
            crit.addOrder(Order.asc("name"));
            return crit.list();
        }/*from ww w .j a  v  a2 s. c o  m*/
    });
    // filter out amendments for other studies
    for (Iterator<Amendment> it = results.iterator(); it.hasNext();) {
        Amendment result = it.next();
        if (!study.hasAmendment(result))
            it.remove();
    }
    if (results.size() == 0) {
        return null;
    } else if (results.size() > 1) {
        // if there's one with this date and no name, it matches
        for (Amendment result : results)
            if (result.getName() == null)
                return result;

        List<String> resultKeys = new ArrayList<String>(results.size());
        for (Amendment result : results)
            resultKeys.add(result.getNaturalKey());
        throw new StudyCalendarValidationException(
                "More than one amendment could match %s: %s.  Please be more specific.", key,
                StringUtils.join(resultKeys.iterator(), ", "));
    } else {
        return results.get(0);
    }
}

From source file:edu.nps.moves.mmowgli.AbstractMmowgliControllerHelper.java

License:Open Source License

private Criteria getExplorationLessThanTL(Float f) {
    if (f == null)
        return null;
    Criteria crit = HSess.get().createCriteria(User.class).add(Restrictions.eq("gameMaster", false))
            .add(Restrictions.lt("basicScore", f)).addOrder(Order.desc("basicScore"));
    return crit;//from   w w  w. j  a  v a  2 s  .com
}

From source file:edu.nps.moves.mmowgli.AbstractMmowgliControllerHelper.java

License:Open Source License

private Criteria getImplementationLessThanTL(Float f) {
    if (f == null)
        return null;
    Criteria crit = HSess.get().createCriteria(User.class).add(Restrictions.eq("gameMaster", false))
            .add(Restrictions.lt("innovationScore", f)).addOrder(Order.desc("innovationScore"));
    return crit;/*from   w  ww  . ja  va2  s  .c om*/
}

From source file:edu.nps.moves.mmowgli.modules.registrationlogin.RegistrationPagePopupFirst.java

License:Open Source License

@SuppressWarnings("unchecked")
public static Criterion getIntervalRestrictionTL() {
    Game game = Game.getTL();//ww w  . jav a  2  s  .com
    if (!game.isRestrictByQueryListInterval())
        return null;

    Date startDate = null, endDate = null;

    Session piiSess = VHibPii.getASession();
    List<Query2Pii> lis = piiSess.createCriteria(Query2Pii.class)
            .add(Restrictions.eq(QUERY_MARKER_FIELD, QUERY_START_MARKER)).list();
    if (!lis.isEmpty())
        startDate = lis.get(0).getDate();

    lis = piiSess.createCriteria(Query2Pii.class).add(Restrictions.eq(QUERY_MARKER_FIELD, QUERY_END_MARKER))
            .list();
    piiSess.close();

    if (!lis.isEmpty())
        endDate = lis.get(0).getDate();

    if (startDate == null) {
        if (endDate == null)
            return null;
        return Restrictions.lt("date", endDate);
    } else {
        if (endDate == null)
            return Restrictions.gt("date", startDate);
        else
            return Restrictions.between("date", startDate, endDate);
    }
}

From source file:es.emergya.bbdd.dao.HistoricoGPSHome.java

License:Open Source License

/**
 * Obtiene las posiciones histricas del recurso indicado durante el periodo
 * pasado como parmetro. Slo consulta la base de datos, no los GPX.
 * /*  w  ww  .  jav  a2 s.c  om*/
 * @param recurso
 * @param inicio
 * @param fin
 * @return la lista de posiciones histricas del recurso ordenadas por marca
 *         temporal ascentente
 */
@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true, rollbackFor = Throwable.class)
public List<HistoricoGPS> getPosicionesEnIntervaloSoloBBDD(String recurso, Date inicio, Date fin) {
    List<HistoricoGPS> result = new LinkedList<HistoricoGPS>();
    try {
        Criteria crit = getSession().createCriteria(HistoricoGPS.class);

        if (inicio != null) {
            crit.add(Restrictions.ge("marcaTemporal", inicio));
        }
        if (fin != null) {
            crit.add(Restrictions.lt("marcaTemporal", fin));
        }

        crit.add(Restrictions.eq("recurso", recurso)).addOrder(Order.asc("marcaTemporal"));

        result = crit.list();
    } catch (Throwable t) {
        log.error("Error al extraer posiciones solo BBDD en intervalo. Recurso=" + recurso + ", Inicio= "
                + inicio + ", Fin= " + fin, t);

    }

    return result;
}

From source file:es.itecban.deployment.environmentmanager.manager.DBCleanerImpl.java

License:Apache License

/**
 * Cleans all the photos except one for a date interval Vamos da a da
 * borrando//from  w w  w.j a v a 2s . c o  m
 */

@Override
public int clean(XMLGregorianCalendar minDate, XMLGregorianCalendar maxDate) throws Exception {

    logger.info("Beginning the cleannin of data.");
    final Session session = this.sessionFactory.openSession();
    int i = 0;
    List<DeploymentTargetType> environmentList = null;
    try {
        String[] environmentNameArray = this.getEnvironmentsName();
        // For each of the environments...
        for (String environmentName : environmentNameArray) {
            XMLGregorianCalendar minDateAux = new XMLGregorianCalendarImpl();
            minDateAux.setDay(minDate.getDay());
            minDateAux.setMonth(minDate.getMonth());
            minDateAux.setYear(minDate.getYear());
            boolean moreDays = true;
            while (moreDays) {
                Criteria dttCriteria = session.createCriteria(DeploymentTargetType.class);
                // cuando no hay fecha es null o es ""??
                if (minDateAux != null)
                    dttCriteria.add(Restrictions.ge("timestamp", minDateAux));

                XMLGregorianCalendar maxDateRelative = new XMLGregorianCalendarImpl();
                //               maxDateRelative.setDay(minDateAux.getDay());
                maxDateRelative.setMonth(minDateAux.getMonth());
                maxDateRelative.setYear(minDateAux.getYear());

                maxDateRelative.setDay(minDateAux.getDay() + 1);
                Object lastDayPhoto = null;
                if (maxDate != null && maxDateRelative.compare(maxDate) == DatatypeConstants.LESSER
                        || maxDateRelative.compare(maxDate) == DatatypeConstants.EQUAL) {
                    lastDayPhoto = this.getLastEnvironmentDayDate(environmentName, minDateAux, maxDateRelative);
                } else {
                    moreDays = false;
                }
                // OJO mirar que pasa y tratar cuando el intervalo es abierto
                dttCriteria.add(Restrictions.lt("timestamp", lastDayPhoto));
                dttCriteria.add(Restrictions.eq("name", environmentName));
                dttCriteria.setMaxResults(3);
                boolean more = true;
                while (more && moreDays) {
                    session.beginTransaction();
                    environmentList = dttCriteria.setMaxResults(3).list();
                    if (environmentList.size() < 3)
                        more = false;
                    for (DeploymentTargetType environment : environmentList) {
                        session.delete(environment);
                        i++;
                    }
                    // Check if there is more to delete
                    session.getTransaction().commit();

                }
                minDateAux.setDay(minDateAux.getDay() + 1);
            }
        }
    } catch (Exception e) {
        logger.severe("Error while deleting the environment from the database" + e);
        throw new Exception("Error while deleting the environment from the database" + e);
    } finally {
        session.close();
    }
    logger.info("Finished the cleannin of data.");
    return i;
}

From source file:es.itecban.deployment.environmentmanager.manager.DBCleanerImpl.java

License:Apache License

/**
 * Cleans all the photos of a date interval
 */// w  w  w. ja v  a2  s  . c om

// @Override
// public int clean(XMLGregorianCalendar minDate, XMLGregorianCalendar
// maxDate) throws Exception {
//
// logger.info("Beginning the cleannin of data.");
// final Session session = this.sessionFactory.openSession();
// int i = 0;
// List<DeploymentTargetType> environmentList = null;
// try {
// Criteria dttCriteria = session
// .createCriteria(DeploymentTargetType.class);
// // cuando no hay fecha es null o es ""??
// if (minDate != null)
// dttCriteria.add(Restrictions.ge("timestamp", minDate));
// if (maxDate != null)
// dttCriteria.add(Restrictions.le("timestamp", maxDate));
// dttCriteria.setMaxResults(3);
// boolean more = true;
//         
// while (more){
// session.beginTransaction();
// environmentList = dttCriteria.setMaxResults(3).list();
// if (environmentList.size() < 3)
// more = false;
// for (DeploymentTargetType environment : environmentList) {
// session.delete(environment);
// i++;
// }
// // Check if there is more to delete
// session.getTransaction().commit();
//            
// }
// } catch (Exception e) {
// logger.severe("Error while deleting the environment from the database"
// + e);
// throw new Exception(
// "Error while deleting the environment from the database" + e);
// } finally {
// session.close();
// }
// logger.info("Finished the cleannin of data.");
// return i;
// }
private Object getLastEnvironmentDayDate(String environmentName, XMLGregorianCalendar minDate,
        XMLGregorianCalendar maxDate) {

    final Session session = this.sessionFactory.openSession();
    session.beginTransaction();

    // Get the latest date for the "photos" stored in the database
    Criteria timestampCriteria = session.createCriteria(DeploymentTargetType.class);

    if (minDate != null)
        timestampCriteria.add(Restrictions.ge("timestamp", minDate));
    if (maxDate != null)
        timestampCriteria.add(Restrictions.lt("timestamp", maxDate));

    timestampCriteria.setProjection(Projections.projectionList().add(Projections.max("timestamp")));
    timestampCriteria.add(Restrictions.eq("name", environmentName));
    Object lastEvironmentTimestampCriteria = timestampCriteria.uniqueResult();

    session.close();
    return lastEvironmentTimestampCriteria;
}

From source file:es.jpons.persistence.query.CriteriaAllenRelations.java

License:Open Source License

/**
 * Returns a criteria for the before allen relation. This models the
 * relation: record.pvp before query.pvp
 *
 * @param initializedCriteria an initialized instance of a criteria
 * @param pvp a possibilistic valid time period
 * @return A criteria with the before operation implemented.
 *///from   www  .  j  a v a  2 s  . c  o m
public static Criteria before(Criteria initializedCriteria, PossibilisticVTP pvp) {
    initializedCriteria = initializedCriteria.add(Restrictions.lt("pvp.endMP", pvp.getStartMP()));

    return initializedCriteria;
}

From source file:es.jpons.persistence.TemporalPersistenceManager.java

License:Open Source License

/**
 * Function that stablishes the constrains for the temporal insertion.
 *
 * @param c An initialized criteria object.
 * @param validTime The valid time to intert
 * @return A criteria to query the database.
 *///from www .j av a  2  s .co  m
protected Criteria criteriaInsert(Criteria c, PossibilisticVTP validTime, TemporalPK key) {

    if (c == null) {
        return null;
    }
    c = c.add(Restrictions.and(Restrictions.gt("pvp.startMP", validTime.getStartMP()),
            Restrictions.or(
                    Restrictions.and(Restrictions.lt("pvp.startMP", validTime.getEndMP()),
                            Restrictions.gt("pvp.endMP", validTime.getEndMP())),
                    Restrictions.lt("pvp.endMP", validTime.getEndMP())),
            Restrictions.eq("tid.id", key.getId())));

    return c;
}