Example usage for org.hibernate ScrollMode FORWARD_ONLY

List of usage examples for org.hibernate ScrollMode FORWARD_ONLY

Introduction

In this page you can find the example usage for org.hibernate ScrollMode FORWARD_ONLY.

Prototype

ScrollMode FORWARD_ONLY

To view the source code for org.hibernate ScrollMode FORWARD_ONLY.

Click Source Link

Document

Requests a scrollable result that is only scrollable forwards.

Usage

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)
 *//* ww  w . ja va2 s  .c om*/
@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)
 *//*  w  ww.  j  a v  a  2  s.  com*/
@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);/*from  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));
            }//from w  w  w.j ava 2 s  .co  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");
    }
}

From source file:org.opentaps.search.IndexingService.java

License:Open Source License

/**
 * Creates the hibernate search index for a given Entity class.
 * @param fullTextSession a <code>FullTextSession</code> value
 * @param entityClass a <code>Class</code> value
 *///from  www .  j  a  v  a2s.c  o  m
@SuppressWarnings("unchecked")
private void createIndexForEntity(FullTextSession fullTextSession, Class entityClass) {
    Criteria query = fullTextSession.createCriteria(entityClass)
            //load necessary associations
            .setFetchMode("distributor", FetchMode.JOIN)
            //distinct them (due to collection load)
            .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
            //set flush mode, ensure it will write to disk on commit the transaction
            .setFlushMode(FlushMode.COMMIT)
            //minimize cache interaction
            .setCacheMode(CacheMode.IGNORE).setFetchSize(Session.FETCH_SIZE);
    //scroll in forward only
    ScrollableResults scroll = query.scroll(ScrollMode.FORWARD_ONLY);
    int batch = 0;
    while (scroll.next()) {
        batch++;
        fullTextSession.index(scroll.get(0));
        if (batch % Session.FETCH_SIZE == 0) {
            // batch flush index into session per FETCH_SIZE
            fullTextSession.flushToIndexes();
            fullTextSession.clear();
        }
    }
    // flush last changes
    fullTextSession.flushToIndexes();
    fullTextSession.getSearchFactory().optimize(entityClass);
}

From source file:org.openvpms.component.business.dao.hibernate.im.IMObjectDAOHibernate.java

License:Open Source License

/**
 * Counts the total no. of rows that would be returned by a named query.
 *
 * @param name    the query name//from   w  w w  . ja  va 2 s.  c  om
 * @param params  the query parameters
 * @param session the session
 * @return the total no. of rows that would be returned by the query
 * @throws IMObjectDAOException a runtime exception, raised if the request
 *                              cannot complete.
 */
private int countNamedQuery(String name, Params params, Session session) {
    Query query = session.getNamedQuery(name);
    params.setParameters(query);

    int result = 0;
    ScrollableResults results = null;
    try {
        results = query.scroll(ScrollMode.FORWARD_ONLY);
        if (results.last()) {
            result = results.getRowNumber() + 1;
        }
    } finally {
        if (results != null) {
            results.close();
        }
    }
    return result;
}

From source file:org.paxle.data.db.impl.CommandDB.java

License:Open Source License

private List<ICommand> fetchNextCommands(int limit) {
    List<ICommand> result = new ArrayList<ICommand>();

    Session session = null;/*from   ww w .  j  a  v  a 2s  .c  o  m*/
    Transaction transaction = null;
    try {
        session = this.sessionFactory.openSession();
        session.setFlushMode(FlushMode.COMMIT);
        session.setCacheMode(CacheMode.IGNORE);
        transaction = session.beginTransaction();

        Query query = session.createQuery("FROM EnqueuedCommand as cmd");
        query.setFetchSize(limit); // this is important for derby because there is no limit support
        query.setMaxResults(limit); // restricting number of returned results
        query.setReadOnly(true); // read-only query
        ScrollableResults sr = query.scroll(ScrollMode.FORWARD_ONLY);

        final Key key = new Key();
        final DynamicBloomFilter bloomFilter = this.bloomFilter;
        final Cache urlExistsCache = this.urlExistsCache;

        // loop through the available commands
        while (sr.next() && result.size() < limit) {
            ICommand cmd = (ICommand) sr.get()[0];

            /* mark command as enqueued */
            session.delete("EnqueuedCommand", cmd);
            session.saveOrUpdate("CrawledCommand", cmd);

            // add command-location into caches
            key.set(cmd.getLocation().toString().getBytes(UTF8), 1.0);
            bloomFilter.add(key);
            Element element = new Element(cmd.getLocation(), null);
            urlExistsCache.put(element);

            result.add(cmd);
        }
        sr.close();

        transaction.commit();
    } catch (Exception e) {
        if (transaction != null && transaction.isActive())
            transaction.rollback();
        this.logger.error("Error while fetching commands", e);
    } finally {
        // closing session
        if (session != null)
            try {
                session.close();
            } catch (Exception e) {
                this.logger.error(
                        String.format("Unexpected '%s' while closing session.", e.getClass().getName()), e);
            }
    }

    return result;
}

From source file:org.pentaho.reporting.engine.classic.extensions.datasources.hibernate.SimpleHQLDataFactory.java

License:Open Source License

/**
 * Queries a datasource. The string 'query' defines the name of the query. The Parameterset given here may contain
 * more data than actually needed./*from www  .  ja v a  2s .  co m*/
 * <p/>
 * The dataset may change between two calls, do not assume anything!
 *
 * @param query
 * @param parameters
 * @return
 */
public synchronized TableModel queryData(final String query, final DataRow parameters)
        throws ReportDataFactoryException {
    try {
        final Query pstmt = getSession().createQuery(query);
        final String[] params = pstmt.getNamedParameters();
        for (int i = 0; i < params.length; i++) {
            final String param = params[i];
            final Object pvalue = parameters.get(param);
            if (pvalue == null) {
                // this should work, but some driver are known to die here.
                // they should be fed with setNull(..) instead; something
                // we cant do as JDK1.2's JDBC does not define it.
                pstmt.setParameter(param, null);
            } else {
                pstmt.setParameter(param, pvalue);
            }
        }

        final Object queryLimit = parameters.get(DataFactory.QUERY_LIMIT);
        if (queryLimit instanceof Number) {
            final Number i = (Number) queryLimit;
            if (i.intValue() >= 0) {
                pstmt.setMaxResults(i.intValue());
            }
        }
        final Object queryTimeout = parameters.get(DataFactory.QUERY_TIMEOUT);
        if (queryTimeout instanceof Number) {
            final Number i = (Number) queryLimit;
            if (i.intValue() >= 0) {
                pstmt.setTimeout(i.intValue());
            }
        }
        final ScrollableResults res = pstmt.scroll(ScrollMode.FORWARD_ONLY);
        return generateDefaultTableModel(res, pstmt.getReturnAliases());
    } catch (Exception e) {
        throw new ReportDataFactoryException("Failed at query: " + query, e);
    }
}

From source file:org.projectforge.database.DatabaseDao.java

License:Open Source License

private long reindexObjects(final Class<?> clazz, final ReindexSettings settings) {
    final Session session = getSession();
    Criteria criteria = createCriteria(session, clazz, settings, true);
    final Long number = (Long) criteria.uniqueResult(); // Get number of objects to re-index (select count(*) from).
    final boolean scrollMode = number > MIN_REINDEX_ENTRIES_4_USE_SCROLL_MODE ? true : false;
    log.info("Starting re-indexing of " + number + " entries (total number) of type " + clazz.getName()
            + " with scrollMode=" + scrollMode + "...");
    final int batchSize = 1000;// NumberUtils.createInteger(System.getProperty("hibernate.search.worker.batch_size")
    final FullTextSession fullTextSession = Search.getFullTextSession(session);
    fullTextSession.setFlushMode(FlushMode.MANUAL);
    fullTextSession.setCacheMode(CacheMode.IGNORE);
    long index = 0;
    if (scrollMode == true) {
        // Scroll-able results will avoid loading too many objects in memory
        criteria = createCriteria(fullTextSession, clazz, settings, false);
        final ScrollableResults results = criteria.scroll(ScrollMode.FORWARD_ONLY);
        while (results.next() == true) {
            final Object obj = results.get(0);
            if (obj instanceof ExtendedBaseDO<?>) {
                ((ExtendedBaseDO<?>) obj).recalculate();
            }//from   ww w.  j a v  a  2  s .c  om
            fullTextSession.index(obj); // index each element
            if (index++ % batchSize == 0)
                session.flush(); // clear every batchSize since the queue is processed
        }
    } else {
        criteria = createCriteria(session, clazz, settings, false);
        final List<?> list = criteria.list();
        for (final Object obj : list) {
            if (obj instanceof ExtendedBaseDO<?>) {
                ((ExtendedBaseDO<?>) obj).recalculate();
            }
            fullTextSession.index(obj);
            if (index++ % batchSize == 0)
                session.flush(); // clear every batchSize since the queue is processed
        }
    }
    final SearchFactory searchFactory = fullTextSession.getSearchFactory();
    searchFactory.optimize(clazz);
    log.info("Re-indexing of " + index + " objects of type " + clazz.getName() + " done.");
    return index;
}

From source file:org.projectforge.framework.persistence.database.DatabaseDao.java

License:Open Source License

private long reindexObjects(final Class<?> clazz, final ReindexSettings settings) {
    final Session session = sessionFactory.getCurrentSession();
    Criteria criteria = createCriteria(session, clazz, settings, true);
    final Long number = (Long) criteria.uniqueResult(); // Get number of objects to re-index (select count(*) from).
    final boolean scrollMode = number > MIN_REINDEX_ENTRIES_4_USE_SCROLL_MODE ? true : false;
    log.info("Starting re-indexing of " + number + " entries (total number) of type " + clazz.getName()
            + " with scrollMode=" + scrollMode + "...");
    final int batchSize = 1000;// NumberUtils.createInteger(System.getProperty("hibernate.search.worker.batch_size")
    final FullTextSession fullTextSession = Search.getFullTextSession(session);
    HibernateCompatUtils.setFlushMode(fullTextSession, FlushMode.MANUAL);
    HibernateCompatUtils.setCacheMode(fullTextSession, CacheMode.IGNORE);
    long index = 0;
    if (scrollMode == true) {
        // Scroll-able results will avoid loading too many objects in memory
        criteria = createCriteria(fullTextSession, clazz, settings, false);
        final ScrollableResults results = criteria.scroll(ScrollMode.FORWARD_ONLY);
        while (results.next() == true) {
            final Object obj = results.get(0);
            if (obj instanceof ExtendedBaseDO<?>) {
                ((ExtendedBaseDO<?>) obj).recalculate();
            }/*from   w w  w .j  a  v  a  2s .  c om*/
            HibernateCompatUtils.index(fullTextSession, obj);
            if (index++ % batchSize == 0) {
                session.flush(); // clear every batchSize since the queue is processed
            }
        }
    } else {
        criteria = createCriteria(session, clazz, settings, false);
        final List<?> list = criteria.list();
        for (final Object obj : list) {
            if (obj instanceof ExtendedBaseDO<?>) {
                ((ExtendedBaseDO<?>) obj).recalculate();
            }
            HibernateCompatUtils.index(fullTextSession, obj);
            if (index++ % batchSize == 0) {
                session.flush(); // clear every batchSize since the queue is processed
            }
        }
    }
    final SearchFactory searchFactory = fullTextSession.getSearchFactory();
    searchFactory.optimize(clazz);
    log.info("Re-indexing of " + index + " objects of type " + clazz.getName() + " done.");
    return index;
}