Example usage for org.hibernate Criteria scroll

List of usage examples for org.hibernate Criteria scroll

Introduction

In this page you can find the example usage for org.hibernate Criteria scroll.

Prototype

public ScrollableResults scroll(ScrollMode scrollMode) throws HibernateException;

Source Link

Document

Get the results as an instance of ScrollableResults based on the given scroll mode.

Usage

From source file:org.eurekastreams.server.persistence.mappers.cache.DomainGroupCacheLoader.java

License:Apache License

/**
 * Query all domain groups, loading them in the cache.
 *//*from  w  ww . j  ava 2 s  .com*/
private void queryAllDomainGroups() {
    long start = System.currentTimeMillis();
    log.info("Loading up all domain groups with a single query");

    Criteria criteria = domainGroupQueryStrategy.getCriteria(getHibernateSession());

    // page the data
    criteria.setFetchSize(FETCH_SIZE);
    criteria.setCacheMode(CacheMode.IGNORE);
    ScrollableResults scroll = criteria.scroll(ScrollMode.FORWARD_ONLY);

    // loop through the results and store in cache
    long recordCounter = 0;
    while (scroll.next()) {
        if (++recordCounter % FETCH_SIZE == 0) {
            log.info("Loading " + recordCounter + "th domainGroup record, clearing session.");
            getHibernateSession().clear();
        }

        DomainGroupModelView result = (DomainGroupModelView) scroll.get(0);
        getCache().set(CacheKeys.GROUP_BY_ID + result.getEntityId(), result);
        getCache().set(CacheKeys.GROUP_BY_SHORT_NAME + result.getShortName(), result.getEntityId());
    }

    log.info("Completed loading all domain groups in " + (System.currentTimeMillis() - start)
            + " milliseconds.");
}

From source file:org.eurekastreams.server.persistence.mappers.cache.PersonCacheLoader.java

License:Apache License

/**
 * Query the database for all people, only requesting the fields that we're caching, paging for effeciency.
 *///w  w  w  .j  av  a 2 s.  c o  m
private void queryAllPeople() {
    Criteria criteria = personQueryStrategy.getCriteria(getHibernateSession());

    // page the data
    criteria.setFetchSize(FETCH_SIZE);
    criteria.setCacheMode(CacheMode.IGNORE);
    ScrollableResults scroll = criteria.scroll(ScrollMode.FORWARD_ONLY);

    // loop through the results and store in cache
    long recordCounter = 0;
    while (scroll.next()) {
        if (++recordCounter % FETCH_SIZE == 0) {
            log.info("Loading " + recordCounter + "th person record, clearing session.");
            getHibernateSession().clear();
        }

        PersonModelView result = (PersonModelView) scroll.get(0);

        getCache().set(CacheKeys.PERSON_BY_ID + result.getEntityId(), result);
        getCache().set(CacheKeys.PERSON_BY_ACCOUNT_ID + result.getAccountId(), result.getEntityId());
        getCache().set(CacheKeys.PERSON_BY_OPEN_SOCIAL_ID + result.getOpenSocialId(), result.getEntityId());
    }
}

From source file:org.geolatte.featureserver.dbase.StandardFeatureReader.java

License:Open Source License

private void scroll(Criteria crit) {
    crit.setFetchSize(1024);
    results = crit.scroll(ScrollMode.FORWARD_ONLY);
}

From source file:org.glite.security.voms.admin.persistence.dao.hibernate.AuditSearchDAOHibernate.java

License:Apache License

public ScrollableAuditLogSearchResults scrollEventsMatchingParams(AuditLogSearchParams sp, ScrollMode mode) {

    Criteria crit = buildCriteriaFromParams(sp);
    ScrollableResults results = crit.scroll(mode);

    return new ScrollableAuditLogSearchResults(sp, results);

}

From source file:org.openmrs.module.amrsreports.db.hibernate.MohHibernateCoreDAO.java

License:Open Source License

/**
 * post-process a list of observations from a criteria; duplicate data FTL
 *
 * @param criteria            the object with data in it
 * @param mohFetchRestriction information for limiting fetch, specifically the size
 * @return a list of processed (cleaned) observations
 *///from   w  w w . ja  v a2 s.  co m
private List<Obs> processObs(Criteria criteria, MohFetchRestriction mohFetchRestriction) {
    List<Obs> observations = new ArrayList<Obs>();

    // TODO: further optimization would be adding start date and end date parameter in the obs restrictions
    ScrollableResults scrollableResults = criteria.scroll(ScrollMode.FORWARD_ONLY);

    Integer size = mohFetchRestriction.getSize();

    // scroll the results
    Obs processedObs = null;
    while (scrollableResults.next() && OpenmrsUtil.compareWithNullAsGreatest(observations.size(), size) == -1) {
        Obs obs = (Obs) scrollableResults.get(0);
        // TODO: thanks to Ampath for the duplicate data, we need to sanitize the query results here
        if (processedObs != null && !obs.isObsGrouping()) {
            if (DateUtils.isSameDay(processedObs.getObsDatetime(), obs.getObsDatetime())
                    && OpenmrsUtil.nullSafeEquals(processedObs.getConcept(), obs.getConcept())
                    && OpenmrsUtil.nullSafeEquals(processedObs.getValueCoded(), obs.getValueCoded())
                    && (OpenmrsUtil.nullSafeEquals(processedObs.getValueNumeric(), obs.getValueNumeric()))) {
                continue;
            }
        }
        processedObs = obs;
        observations.add(obs);
    }
    scrollableResults.close();
    return observations;
}

From source file:org.openmrs.module.amrsreports.db.hibernate.MohHibernateCoreDAO.java

License:Open Source License

/**
 * @see MohCoreDAO#getPatientEncounters(Integer, java.util.Map, org.openmrs.module.amrsreports.util.MohFetchRestriction, java.util.Date)
 *///  www. ja va  2  s  . c  o m
@Override
public List<Encounter> getPatientEncounters(final Integer patientId,
        final Map<String, Collection<OpenmrsObject>> restrictions,
        final MohFetchRestriction mohFetchRestriction, final Date evaluationDate) throws DAOException {
    // create a hibernate criteria on the encounter object
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Encounter.class);
    // restrict the encounter that will be returned to specific patient only
    criteria.add(Restrictions.eq("patientId", patientId));

    // default ordering for the returned encounter is descending on encounter datetime
    Order order = Order.desc("encounterDatetime");
    // change the default ordering if the user pass the ascending ordering in the parameters
    if (OpenmrsUtil.nullSafeEquals(MohFetchOrdering.ORDER_ASCENDING, mohFetchRestriction.getFetchOrdering())) {
        order = Order.asc("encounterDatetime");
    }
    // add the ordering object to the criteria
    criteria.addOrder(order);

    // make sure we don't go past the evaluationDate
    criteria.add(Restrictions.le("encounterDatetime", evaluationDate));

    // always get from the first result
    criteria.setFirstResult(0);
    // set the first result to a number if the user pass any value on this parameter (currently not being used)
    if (mohFetchRestriction.getStart() != null) {
        criteria.setFirstResult(mohFetchRestriction.getStart());
    }

    // specify how many records should be returned
    if (mohFetchRestriction.getSize() != null) {
        criteria.setMaxResults(mohFetchRestriction.getSize());
    }

    // create a dummy encounter object
    Encounter encounter = new Encounter();
    // iterate over each property in the restriction map
    for (String property : restrictions.keySet()) {
        // get the actual object that will restrict the encounter. this will contains the list of encounter type or list of location
        // or list of provider (currently not being used) passed from caller
        Collection<OpenmrsObject> propertyValues = restrictions.get(property);
        // check to make sure the list is not empty and the property is readable. example of the property for encounter are
        // encounterType or location of the encounter
        if (CollectionUtils.isNotEmpty(propertyValues) && PropertyUtils.isReadable(encounter, property)) {
            // create a restriction on the property with the above list as the value
            criteria.add(Restrictions.in(property, propertyValues));
            // add ordering on that property to prevent slowness when ordering only on encounter datetime (1.6.x only)
            criteria.addOrder(Order.asc(property));
        }
    }

    // exclude all voided encounters
    criteria.add(Restrictions.eq("voided", Boolean.FALSE));

    List<Encounter> encounters = new ArrayList<Encounter>();

    // scroll the results and add them to the above list of encounter
    Integer counter = 0;
    ScrollableResults scrollableResults = criteria.scroll(ScrollMode.FORWARD_ONLY);
    while (scrollableResults.next()) {
        encounters.add((Encounter) scrollableResults.get(0));
    }
    scrollableResults.close();
    return encounters;
}

From source file:org.openmrs.module.clinicalsummary.db.hibernate.HibernateCoreDAO.java

License:Open Source License

/**
 * @see CoreDAO#getPatientObservations(Integer, java.util.Map, org.openmrs.module.clinicalsummary.util.FetchRestriction)
 *//*from  ww  w.java2 s . c  o m*/
@Override
public List<Obs> getPatientObservations(final Integer patientId,
        final Map<String, Collection<OpenmrsObject>> restrictions, final FetchRestriction fetchRestriction)
        throws DAOException {
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Obs.class);
    criteria.createAlias("person", "person");
    criteria.add(Restrictions.eq("person.personId", patientId));

    criteria.setFirstResult(0);
    if (fetchRestriction.getStart() != null)
        criteria.setFirstResult(fetchRestriction.getStart());

    if (fetchRestriction.getSize() != null && fetchRestriction.getSize() == 1)
        criteria.setMaxResults(fetchRestriction.getSize());

    Order order = Order.desc("obsDatetime");
    if (OpenmrsUtil.nullSafeEquals(FetchOrdering.ORDER_ASCENDING, fetchRestriction.getFetchOrdering()))
        order = Order.asc("obsDatetime");

    criteria.addOrder(order);

    Obs observation = new Obs();
    for (String property : restrictions.keySet()) {
        Collection<OpenmrsObject> propertyValues = restrictions.get(property);
        if (CollectionUtils.isNotEmpty(propertyValues) && PropertyUtils.isReadable(observation, property)) {
            criteria.add(Restrictions.in(property, propertyValues));
            criteria.addOrder(Order.asc(property));
        }
    }

    criteria.add(Restrictions.eq("voided", Boolean.FALSE));

    List<Obs> observations = new ArrayList<Obs>();

    // TODO: further optimization would be adding start date and end date parameter in the obs restrictions
    ScrollableResults scrollableResults = criteria.scroll(ScrollMode.FORWARD_ONLY);

    Integer size = fetchRestriction.getSize();

    // scroll the results
    Obs processedObs = null;
    while (scrollableResults.next() && OpenmrsUtil.compareWithNullAsGreatest(observations.size(), size) == -1) {
        Obs obs = (Obs) scrollableResults.get(0);
        // TODO: thanks to Ampath for the duplicate data, we need to sanitize the query results here
        if (processedObs != null && !obs.isObsGrouping()) {
            if (DateUtils.isSameDay(processedObs.getObsDatetime(), obs.getObsDatetime())
                    && OpenmrsUtil.nullSafeEquals(processedObs.getConcept(), obs.getConcept())
                    && OpenmrsUtil.nullSafeEquals(processedObs.getValueCoded(), obs.getValueCoded())
                    && (OpenmrsUtil.nullSafeEquals(processedObs.getValueNumeric(), obs.getValueNumeric())))
                continue;
        }
        processedObs = obs;
        observations.add(obs);
    }
    scrollableResults.close();
    return observations;
}

From source file:org.openmrs.module.clinicalsummary.db.hibernate.HibernateCoreDAO.java

License:Open Source License

/**
 * @see CoreDAO#getPatientEncounters(Integer, java.util.Map, org.openmrs.module.clinicalsummary.util.FetchRestriction)
 *//* ww w. j  a v a2  s  .  c  o m*/
@Override
public List<Encounter> getPatientEncounters(final Integer patientId,
        final Map<String, Collection<OpenmrsObject>> restrictions, final FetchRestriction fetchRestriction)
        throws DAOException {
    // create a hibernate criteria on the encounter object
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Encounter.class);
    // restrict the encounter that will be returned to specific patient only
    criteria.createAlias("patient", "patient");
    criteria.add(Restrictions.eq("patient.patientId", patientId));

    // default ordering for the returned encounter is descending on encounter datetime
    Order order = Order.desc("encounterDatetime");
    // change the default ordering if the user pass the ascending ordering in the parameters
    if (OpenmrsUtil.nullSafeEquals(FetchOrdering.ORDER_ASCENDING, fetchRestriction.getFetchOrdering()))
        order = Order.asc("encounterDatetime");
    // add the ordering object to the criteria
    criteria.addOrder(order);

    // always get from the first result
    criteria.setFirstResult(0);
    // set the first result to a number if the user pass any value on this parameter (currently not being used)
    if (fetchRestriction.getStart() != null)
        criteria.setFirstResult(fetchRestriction.getStart());

    // specify how many records should be returned
    if (fetchRestriction.getSize() != null)
        criteria.setMaxResults(fetchRestriction.getSize());

    // create a dummy encounter object
    Encounter encounter = new Encounter();
    // iterate over each property in the restriction map
    for (String property : restrictions.keySet()) {
        // get the actual object that will restrict the encounter. this will contains the list of encounter type or list of location
        // or list of provider (currently not being used) passed from caller
        Collection<OpenmrsObject> propertyValues = restrictions.get(property);
        // check to make sure the list is not empty and the property is readable. example of the property for encounter are
        // encounterType or location of the encounter
        if (CollectionUtils.isNotEmpty(propertyValues) && PropertyUtils.isReadable(encounter, property)) {
            // create a restriction on the property with the above list as the value
            criteria.add(Restrictions.in(property, propertyValues));
            // add ordering on that property to prevent slowness when ordering only on encounter datetime (1.6.x only)
            criteria.addOrder(Order.asc(property));
        }
    }

    // exclude all voided encounters
    criteria.add(Restrictions.eq("voided", Boolean.FALSE));

    List<Encounter> encounters = new ArrayList<Encounter>();

    // scroll the results and add them to the above list of encounter
    Integer counter = 0;
    ScrollableResults scrollableResults = criteria.scroll(ScrollMode.FORWARD_ONLY);
    while (scrollableResults.next())
        encounters.add((Encounter) scrollableResults.get(0));
    scrollableResults.close();
    return encounters;
}

From source file:org.openspaces.persistency.hibernate.iterator.DefaultScrollableDataIterator.java

License:Open Source License

protected ScrollableResults createCursor() {
    session = sessionFactory.openSession();
    session.setFlushMode(FlushMode.MANUAL);
    transaction = session.beginTransaction();
    if (entityName != null) {
        Criteria criteria = session.createCriteria(entityName);
        criteria.setCacheable(false);/* w w w  .j  a  v  a2  s.c  o  m*/
        criteria.setFlushMode(FlushMode.MANUAL);
        criteria.setFetchSize(fetchSize);
        if (perfromOrderById) {
            ClassMetadata metadata = sessionFactory.getClassMetadata(entityName);
            String idPropName = metadata.getIdentifierPropertyName();
            if (idPropName != null) {
                criteria.addOrder(Order.asc(idPropName));
            }
        }
        if (from >= 0) {
            if (from > 0)
                criteria.setFirstResult(from);
            criteria.setMaxResults(size);
        }
        return criteria.scroll(ScrollMode.FORWARD_ONLY);
    } else if (sqlQuery != null) {
        Query query = HibernateIteratorUtils.createQueryFromSQLQuery(sqlQuery, session);
        query.setFetchSize(fetchSize);
        if (from >= 0) {
            if (from > 0)
                query.setFirstResult(from);
            query.setMaxResults(size);
        }
        return query.scroll(ScrollMode.FORWARD_ONLY);
    } else if (hQuery != null) {
        Query query = session.createQuery(hQuery);
        query.setFetchSize(fetchSize);
        if (from >= 0) {
            if (from > 0)
                query.setFirstResult(from);
            query.setMaxResults(size);
        }
        query.setCacheMode(CacheMode.IGNORE);
        query.setCacheable(false);
        query.setReadOnly(true);
        return query.scroll(ScrollMode.FORWARD_ONLY);
    } else {
        throw new IllegalStateException("No SQLQuery, entity, or Hibernate Query provided");
    }
}

From source file:org.openspaces.persistency.hibernate.iterator.StatelessScrollableDataIterator.java

License:Open Source License

protected ScrollableResults createCursor() {
    session = sessionFactory.openStatelessSession();
    transaction = session.beginTransaction();
    if (entityName != null) {
        Criteria criteria = session.createCriteria(entityName);
        criteria.setFetchSize(fetchSize);
        if (perfromOrderById) {
            ClassMetadata metadata = sessionFactory.getClassMetadata(entityName);
            String idPropName = metadata.getIdentifierPropertyName();
            if (idPropName != null) {
                criteria.addOrder(Order.asc(idPropName));
            }/*  ww w  .  j  av a 2 s . c o m*/
        }
        if (from >= 0) {
            if (from > 0)
                criteria.setFirstResult(from);
            criteria.setMaxResults(size);
        }
        return criteria.scroll(ScrollMode.FORWARD_ONLY);
    } else if (sqlQuery != null) {
        Query query = HibernateIteratorUtils.createQueryFromSQLQuery(sqlQuery, session);
        query.setFetchSize(fetchSize);
        if (from >= 0) {
            if (from > 0)
                query.setFirstResult(from);
            query.setMaxResults(size);
        }
        return query.scroll(ScrollMode.FORWARD_ONLY);
    } else if (hQuery != null) {
        Query query = session.createQuery(hQuery);
        query.setFetchSize(fetchSize);
        if (from >= 0) {
            if (from > 0)
                query.setFirstResult(from);
            query.setMaxResults(size);
        }
        query.setReadOnly(true);
        return query.scroll(ScrollMode.FORWARD_ONLY);
    } else {
        throw new IllegalStateException("Either SQLQuery or entity must be provided");
    }
}