Example usage for org.hibernate.criterion Restrictions or

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

Introduction

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

Prototype

public static LogicalExpression or(Criterion lhs, Criterion rhs) 

Source Link

Document

Return the disjuction of two expressions

Usage

From source file:modelo.dao.ExamenDAO.java

License:Open Source License

/**
 * Este mtodo sirve para obtener exmenes por el curso seleccionado,
 * obteniendo slo los exmenes pblicos o aquellos hechos por el maestro
 * ingresado y que coincidan con el curso ingresado
 * /*from w  w  w .j av  a2s  .  co m*/
 * @param curso el objeto CursoDTO del que se quieren obtener los
 * exmenes que pertenecen a dicho curso
 * 
 * @param maestro Sirve para filtrar la bsqueda por el
 * autor del examen. Esta consulta regresa los exmenes que pertenezcan
 * al curso y que adems son pblicos o hechos por el maestro.
 * 
 * @return Una lista de ExamenDTO con los exmenes que cumplen las coincidencias
 * o null, en caso de que no haya coincidencias
 */
public List<ExamenDTO> obtenerPublicosPorCurso(CursoDTO curso, UsuarioDTO maestro) {

    Session s = getSession();
    Transaction tx = null;
    List<ExamenDTO> examenes;

    if (s == null) {
        System.out.println("Session nula, regresando null....");
        return null;
    }

    try {
        tx = s.beginTransaction();
        //Obtiene todos los exmenes que coincidan con el curso,
        //sin sus relaciones (claves)
        //Aquellos examenes que sean (publicos o del maestro) y que
        //pertenezcan al curso
        Criteria c = s.createCriteria(ExamenDTO.class, "examen").createAlias("examen.curso", "curso")
                .add(Restrictions.and(Restrictions.eq("curso.nombre", curso.getNombre()),
                        Restrictions.or(Restrictions.eq("examen.permiso", Permiso.Publico),
                                Restrictions.eq("examen.autor", maestro))));

        examenes = c.list();
        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            tx.rollback();
        }
        examenes = null;
    } finally {
        s.close();
        System.out.println("Session cerrada");
    }

    return examenes;
}

From source file:modelo.dao.ExamenDAO.java

License:Open Source License

/**
 * Este mtodo sirve para obtener exmenes por el nombre ingresado,
 * obteniendo slo los exmenes pblicos o aquellos hechos por el maestro
 * ingresado, y que coincidan con el nombre ingresado
 * /*from  w w  w .  j ava2  s  . c o  m*/
 * @param nombre el nombre o parte del nombre del examen utilizado como filtro
 * 
 * @param maestro Sirve para filtrar la bsqueda por el
 * autor del examen. Esta consulta regresa los exmenes que coincidan con el
 * nombre y que adems son pblicos o hechos por el maestro.
 * 
 * @return Una lista de ExamenDTO con los exmenes que cumplen las coincidencias
 * o null, en caso de que no haya coincidencias
 */
public List<ExamenDTO> obtenerPublicosPorNombre(String nombre, UsuarioDTO maestro) {

    Session s = getSession();
    Transaction tx = null;
    List<ExamenDTO> examenes;

    if (s == null) {
        System.out.println("Session nula, regresando null....");
        return null;
    }

    try {
        tx = s.beginTransaction();
        //Obtiene todos los exmenes que coincidan con el nombre,
        //sin sus relaciones (claves)
        //Aquellos examenes que sean (publicos o del maestro) y que
        //coincidan con el nombre
        Criteria c = s.createCriteria(ExamenDTO.class, "examen")
                .add(Restrictions.and(Restrictions.like("examen.nombre", "%" + nombre + "%"),
                        Restrictions.or(Restrictions.eq("examen.permiso", Permiso.Publico),
                                Restrictions.eq("examen.autor", maestro))));

        examenes = c.list();
        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            tx.rollback();
        }
        examenes = null;
    } finally {
        s.close();
        System.out.println("Session cerrada");
    }

    return examenes;
}

From source file:modelo.dao.ExamenDAO.java

License:Open Source License

/**
 * Este mtodo sirve para obtener exmenes por el nombre ingresado y el curso
 * seleccionado obteniendo slo los exmenes pblicos o hechos por el 
 * maestro ingresado, y que coincidan con el nombre ingresado y el curso
 * seleccionado/*from   w w  w  .  j  a va2 s.  c om*/
 * 
 * @param curso el objeto CursoDTO del que se quieren obtener los
 * exmenes que pertenecen a dicho curso
 * @param nombre el nombre o parte del nombre del examen utilizado como filtro
 * 
 * @param maestro Sirve para filtrar la bsqueda por el
 * autor del examen. Esta consulta regresa los exmenes que coincidan con el
 * nombre y el curso y que adems son pblicos o hechos por el maestro.
 * 
 * @return Una lista de ExamenDTO con los exmenes que cumplen las coincidencias
 * o null, en caso de que no haya coincidencias
 */
public List<ExamenDTO> obtenerPublicosPorCursoYNombre(CursoDTO curso, String nombre, UsuarioDTO maestro) {

    Session s = getSession();
    Transaction tx = null;
    List<ExamenDTO> examenes;

    if (s == null) {
        System.out.println("Session nula, regresando null....");
        return null;
    }

    try {
        tx = s.beginTransaction();
        //Obtiene todos los exmenes que coincidan con el curso y el nombre,
        //sin sus relaciones (claves)
        //Aquellos examenes que sean (publicos o del maestro) y que
        //pertenezcan al curso y coincidan con el nombre
        Criteria c = s.createCriteria(ExamenDTO.class, "examen").createAlias("examen.curso", "curso")
                .add(Restrictions.and(
                        Restrictions.and(Restrictions.eq("curso.nombre", curso.getNombre()),
                                Restrictions.like("examen.nombre", "%" + nombre + "%")),
                        Restrictions.or(Restrictions.eq("examen.permiso", Permiso.Publico),
                                Restrictions.eq("examen.autor", maestro))));

        examenes = c.list();
        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            tx.rollback();
        }
        examenes = null;
    } finally {
        s.close();
        System.out.println("Session cerrada");
    }

    return examenes;
}

From source file:moos.ssds.dao.DataProducerDAO.java

License:LGPL

/**
 * This method finds all the deployments of a <code>Device</code> that fall
 * within a certain time window. This is usually done when searching for
 * data from that device./*from ww w.j  ava 2 s  .c o  m*/
 * 
 * @param device
 * @param startDate
 * @param endDate
 * @param orderByPropertyName
 * @param ascendingOrDescending
 * @param returnFullObjectGraph
 * @return
 * @throws MetadataAccessException
 */
public Collection findByDeviceAndTimeWindow(Device device, Date startDate, Date endDate,
        String orderByPropertyName, String ascendingOrDescending, boolean returnFullObjectGraph)
        throws MetadataAccessException {

    // The collection to return
    Collection dataProducersToReturn = new ArrayList();

    // First make sure the device exists
    DeviceDAO deviceDAO = new DeviceDAO(getSession());

    Device persistentDevice = null;
    persistentDevice = (Device) deviceDAO.findEquivalentPersistentObject(device, false);

    if (persistentDevice == null)
        return dataProducersToReturn;

    // Create the criteria
    try {
        Criteria criteria = getSession().createCriteria(DataProducer.class);
        criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
        criteria.add(Restrictions.eq("device", persistentDevice));
        criteria.add(Restrictions.eq("dataProducerType", DataProducer.TYPE_DEPLOYMENT));
        // Add the time criteria
        if (startDate != null) {
            criteria.add(
                    Restrictions.or(Restrictions.gt("endDate", startDate), Restrictions.isNull("endDate")));
        }
        if (endDate != null) {
            criteria.add(
                    Restrictions.or(Restrictions.lt("startDate", endDate), Restrictions.isNull("startDate")));
        }
        addOrderByCriteria(criteria, orderByPropertyName, ascendingOrDescending);
        dataProducersToReturn = criteria.list();
    } catch (HibernateException e) {
        throw new MetadataAccessException(e.getMessage());
    }

    // If the full object graphs are requested
    if (returnFullObjectGraph)
        dataProducersToReturn = getRealObjectsAndRelationships(dataProducersToReturn);

    return dataProducersToReturn;
}

From source file:moos.ssds.dao.DataProducerDAO.java

License:LGPL

/**
 * TODO kgomes document this// w ww .  j  a v  a 2s .c  o m
 * 
 * @param countQuery
 * @param id
 * @param name
 * @param exactNameMatch
 * @param dataProducerType
 * @param startDate
 * @param boundedByStartDate
 * @param endDate
 * @param boundedByEndDate
 * @param geospatialLatMin
 * @param geospatialLatMax
 * @param geospatialLonMin
 * @param geospatialLonMax
 * @param geospatialDepthMin
 * @param geospatialDepthMax
 * @param geospatialBenthicAltitudeMin
 * @param geospatialBenthicAltitudeMax
 * @param hostName
 * @param exactHostNameMatch
 * @param orderByProperty
 * @param ascendOrDescend
 * @return
 * @throws MetadataAccessException
 */
private Criteria formulatePropertyCriteria(boolean countQuery, Long id, String name, boolean exactNameMatch,
        String dataProducerType, Date startDate, boolean boundedByStartDate, Date endDate,
        boolean boundedByEndDate, Double geospatialLatMin, Double geospatialLatMax, Double geospatialLonMin,
        Double geospatialLonMax, Float geospatialDepthMin, Float geospatialDepthMax,
        Float geospatialBenthicAltitudeMin, Float geospatialBenthicAltitudeMax, String hostName,
        boolean exactHostNameMatch, String orderByProperty, String ascendOrDescend)
        throws MetadataAccessException {
    // The Criteria to return
    Criteria criteria = getSession().createCriteria(DataProducer.class);
    // Make it distinct
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    // Check for exceptional conditions on the query
    if ((dataProducerType != null) && (!DataProducer.isValidDataProducerType(dataProducerType)))
        throw new MetadataAccessException("The dataProducerType (" + dataProducerType
                + ") does not match a constant defined in the DataProducer class");
    if ((geospatialLatMin != null) && (geospatialLatMax != null))
        if (geospatialLatMax.doubleValue() < geospatialLatMin.doubleValue())
            throw new MetadataAccessException("The maximum latitude specified was less than the minimum.");
    if ((geospatialLonMin != null) && (geospatialLonMax != null))
        if (geospatialLonMax.doubleValue() < geospatialLonMin.doubleValue())
            throw new MetadataAccessException("The maximum longitude specified was less than the minimum.");
    if ((geospatialDepthMin != null) && (geospatialDepthMax != null))
        if (geospatialDepthMax.doubleValue() < geospatialDepthMin.doubleValue())
            throw new MetadataAccessException("The depth maximum specified was less than the minimum.");
    if ((geospatialBenthicAltitudeMin != null) && (geospatialBenthicAltitudeMax != null))
        if (geospatialBenthicAltitudeMax.doubleValue() < geospatialBenthicAltitudeMin.doubleValue())
            throw new MetadataAccessException(
                    "The benthic altitude maximum specified was less than the minimum.");
    if ((startDate != null) && (endDate != null) && (endDate.before(startDate)))
        throw new MetadataAccessException("The end date specified (" + endDate
                + ") is before the start date specified (" + startDate + ")");

    // Now build the Criteria
    if (id != null) {
        criteria.add(Restrictions.eq("id", id));
    } else {
        if ((name != null) && (!name.equals(""))) {
            if (exactNameMatch) {
                criteria.add(Restrictions.eq("name", name));
            } else {
                criteria.add(Restrictions.like("name", "%" + name + "%"));
            }
        }
        if (dataProducerType != null) {
            criteria.add(Restrictions.eq("dataProducerType", dataProducerType));
        }
        if (startDate != null) {
            criteria.add(
                    Restrictions.or(Restrictions.gt("endDate", startDate), Restrictions.isNull("endDate")));
            if (boundedByStartDate) {
                criteria.add(Restrictions.gt("startDate", startDate));
            }
        }
        if (endDate != null) {
            criteria.add(
                    Restrictions.or(Restrictions.lt("startDate", endDate), Restrictions.isNull("startDate")));
            if (boundedByEndDate) {
                criteria.add(Restrictions.lt("endDate", endDate));
            }
        }
        if (geospatialLatMin != null)
            criteria.add(Restrictions.ge("nominalLatitude", geospatialLatMin));

        if (geospatialLatMax != null)
            criteria.add(Restrictions.le("nominalLatitude", geospatialLatMax));

        if (geospatialLonMin != null)
            criteria.add(Restrictions.ge("nominalLongitude", geospatialLonMin));

        if (geospatialLonMax != null)
            criteria.add(Restrictions.le("nominalLongitude", geospatialLonMax));

        if (geospatialDepthMin != null)
            criteria.add(Restrictions.le("nominalDepth", geospatialDepthMin));

        if (geospatialDepthMax != null)
            criteria.add(Restrictions.ge("nominalDepth", geospatialDepthMax));

        if (geospatialBenthicAltitudeMin != null)
            criteria.add(Restrictions.ge("benthicAltitude", geospatialBenthicAltitudeMin));

        if (geospatialBenthicAltitudeMax != null)
            criteria.add(Restrictions.lt("benthicAltitude", geospatialBenthicAltitudeMax));
        if ((hostName != null) && (!hostName.equals(""))) {
            if (exactHostNameMatch) {
                criteria.add(Restrictions.eq("hostName", hostName));
            } else {
                criteria.add(Restrictions.like("hostName", "%" + hostName + "%"));
            }
        }
    }
    // Setup if a count query, if not add fetching and ordering
    if (countQuery) {
        criteria.setProjection(Projections.rowCount());
    } else {
        addOrderByCriteria(criteria, orderByProperty, ascendOrDescend);
    }
    // Now return the Criteria
    return criteria;
}

From source file:moos.ssds.dao.EventDAO.java

License:LGPL

/**
 * /*www  .  j a v a2  s .  co  m*/
 * @param countQuery
 * @param id
 * @param name
 * @param exactNameMatch
 * @param startDate
 * @param boundedByStartDate
 * @param endDate
 * @param boundedByEndDate
 * @param orderByProperty
 * @param ascendOrDescend
 * @return
 * @throws MetadataAccessException
 */
private Criteria formulatePropertyCriteria(boolean countQuery, Long id, String name, boolean exactNameMatch,
        Date startDate, boolean boundedByStartDate, Date endDate, boolean boundedByEndDate,
        String orderByProperty, String ascendOrDescend) throws MetadataAccessException {

    // The Criteria to return
    Criteria criteria = getSession().createCriteria(Event.class);

    // Make it distinct
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    // Check for exceptional conditions on the query
    if ((startDate != null) && (endDate != null) && (endDate.before(startDate)))
        throw new MetadataAccessException("The end date specified (" + endDate
                + ") is before the start date specified (" + startDate + ")");

    // Now build the Criteria
    if (id != null) {
        criteria.add(Restrictions.eq("id", id));
    } else {
        if ((name != null) && (!name.equals(""))) {
            if (exactNameMatch) {
                criteria.add(Restrictions.eq("name", name));
            } else {
                criteria.add(Restrictions.like("name", "%" + name + "%"));
            }
        }
        if (startDate != null) {
            criteria.add(
                    Restrictions.or(Restrictions.gt("endDate", startDate), Restrictions.isNull("endDate")));
            if (boundedByStartDate) {
                criteria.add(Restrictions.gt("startDate", startDate));
            }
        }
        if (endDate != null) {
            criteria.add(
                    Restrictions.or(Restrictions.lt("startDate", endDate), Restrictions.isNull("startDate")));
            if (boundedByEndDate) {
                criteria.add(Restrictions.lt("endDate", endDate));
            }
        }
    }

    // Setup if a count query, if not add fetching and ordering
    if (countQuery) {
        criteria.setProjection(Projections.rowCount());
    } else {
        addOrderByCriteria(criteria, orderByProperty, ascendOrDescend);
    }

    // Now return the Criteria
    return criteria;
}

From source file:mx.edu.um.mateo.rh.dao.impl.EmpleadoDaoHibernate.java

License:Open Source License

private Criterion getQueryByMonth(Calendar gc) {
    Criterion cr = null;/*from   w ww  .java 2s.co m*/

    gc.add(Calendar.YEAR, 1);

    gc.set(Calendar.DAY_OF_MONTH, 1);
    Date fechaI = gc.getTime();

    gc.set(Calendar.DAY_OF_MONTH, gc.getMaximum(Calendar.DAY_OF_MONTH));
    Date fechaF = gc.getTime();

    cr = Restrictions.between("fechaNacimiento", fechaI, fechaF);

    Calendar tmp = (Calendar) gc.clone();
    tmp.clear();
    tmp.setTime(new Date());
    tmp.add(Calendar.YEAR, -17);

    if (gc.compareTo(tmp) <= 0) {
        return Restrictions.or(cr, getQueryByMonth(gc));
    } else {
        return cr;
    }
}

From source file:mx.edu.um.mateo.rh.dao.impl.SolicitudVacacionesDaoHibernate.java

License:Open Source License

/**
 * @see/*  w w w. j a  v  a 2  s. co m*/
 * mx.edu.um.rh.dao.SolicitudVacacionesDao#getSolicitudesSalida(mx.edu.um.rh.model.SolicitudVacaciones,
 * mx.edu.um.rh.model.SolicitudVacaciones)
 */
@SuppressWarnings("unchecked")
@Override
@Transactional(readOnly = true)
public List<SolicitudVacaciones> getSolicitudesSalida(SolicitudVacaciones ssalidaInicial,
        SolicitudVacaciones ssalidaFinal) throws Exception {
    Criteria sql = getSession().createCriteria(SolicitudVacaciones.class);
    sql.add(Restrictions.eq("empleado", ssalidaInicial.getEmpleado()));
    sql.add(Restrictions.or(
            Restrictions.between("fechaInicial", ssalidaInicial.getFechaInicial(),
                    ssalidaFinal.getFechaInicial()),
            Restrictions.between("fechaFinal", ssalidaInicial.getFechaInicial(),
                    ssalidaFinal.getFechaInicial())));
    sql.add(Restrictions.or(Restrictions.eq("status", Constantes.SOLICITUDSALIDA_STATUS_AUTORIZADO),
            Restrictions.eq("status", Constantes.SOLICITUDSALIDA_STATUS_PRIMA_VACACIONAL)));
    sql.addOrder(Order.asc("fechaInicial"));
    return sql.list();
}

From source file:net.firejack.platform.core.store.AbstractStore.java

License:Apache License

protected Criteria prepareCriteria(Session session, LinkedList<Criterion> criterionList,
        Map<String, String> aliases, Paging paging, boolean isOr, boolean isLeft) {
    Criteria criteria = session.createCriteria(clazz);
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    if (aliases != null && !aliases.isEmpty()) {
        for (Map.Entry<String, String> alias : aliases.entrySet()) {
            criteria.createAlias(alias.getKey(), alias.getValue(),
                    isLeft ? CriteriaSpecification.LEFT_JOIN : CriteriaSpecification.INNER_JOIN);
        }/*from   w  w  w  .  j  av a 2  s. c  o m*/
    }

    if (criterionList != null) {
        Criterion left = null;
        for (Criterion criterion : criterionList) {
            left = criterionList.getFirst() == criterion ? criterion
                    : isOr ? Restrictions.or(left, criterion) : Restrictions.and(left, criterion);

        }
        if (left != null)
            criteria.add(left);
    }

    if (paging != null) {
        if (paging.getLimit() != null && paging.getLimit() > -1) {
            criteria.setMaxResults(paging.getLimit());
        }
        if (paging.getOffset() != null && paging.getOffset() > -1) {
            criteria.setFirstResult(paging.getOffset());
        }
        if (paging.getSortFields() != null) {
            for (SortField sortField : paging.getSortFields()) {
                if (sortField.getSortDirection().equals(SortOrder.ASC)) {
                    criteria.addOrder(Order.asc(sortField.getSortColumn()));
                } else {
                    criteria.addOrder(Order.desc(sortField.getSortColumn()));
                }
            }
        }
    }
    return criteria;
}

From source file:net.firejack.platform.core.store.AbstractStore.java

License:Apache License

protected Integer searchCount(final LinkedList<Criterion> criterions, final Map<String, String> aliases,
        final boolean isOr, final boolean isLeft) {
    return getHibernateTemplate().execute(new HibernateCallback<Integer>() {
        @Override/*from  w w w .  j  a  v a  2 s .  co  m*/
        public Integer doInHibernate(Session session) throws HibernateException, SQLException {
            Criteria criteria = session.createCriteria(clazz);

            if (aliases != null && !aliases.isEmpty()) {
                for (Map.Entry<String, String> alias : aliases.entrySet()) {
                    criteria.createAlias(alias.getKey(), alias.getValue(),
                            isLeft ? CriteriaSpecification.LEFT_JOIN : CriteriaSpecification.INNER_JOIN);
                }
            }

            if (criterions != null) {
                Criterion left = null;
                for (Criterion criterion : criterions) {
                    left = criterions.getFirst() == criterion ? criterion
                            : isOr ? Restrictions.or(left, criterion) : Restrictions.and(left, criterion);
                }
                if (left != null)
                    criteria.add(left);
            }

            return ((Long) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();
        }
    });
}