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.openbravo.test.dal.DalPerformanceCriteriaTest.java

License:Open Source License

@Test
public void testCriteriaScrollable() {

    OBCriteria<BusinessPartner> c = OBDal.getInstance().createCriteria(BusinessPartner.class);
    ScrollableResults iterator = c.scroll(ScrollMode.FORWARD_ONLY);
    iterator.next();//from  w w w .  ja v  a2s . c o  m
}

From source file:org.openbravo.test.dal.DalPerformanceExampleTest.java

License:Open Source License

/**
 * Scrollable results/*  ww w .jav a 2  s.com*/
 */
@Test
public void testSimpleScrollQuery() {
    setTestUserContext();

    final OBCriteria<Product> productCriteria = OBDal.getInstance().createCriteria(Product.class);
    // 1000 is normally a good fetch size
    productCriteria.setFetchSize(1000);
    final ScrollableResults productScroller1 = productCriteria.scroll(ScrollMode.FORWARD_ONLY);
    int i = 0;
    while (productScroller1.next()) {
        final Product product = (Product) productScroller1.get()[0];
        System.err.println(product.getId());
        // clear the session every 100 records
        if ((i % 100) == 0) {
            OBDal.getInstance().getSession().clear();
        }
        i++;
    }

    i = 0;
    final OBQuery<Product> productQuery = OBDal.getInstance().createQuery(Product.class, "");
    // 1000 is normally a good fetch size
    productQuery.setFetchSize(1000);
    final ScrollableResults productScroller2 = productQuery.scroll(ScrollMode.FORWARD_ONLY);
    while (productScroller2.next()) {
        final Product product = (Product) productScroller2.get()[0];
        System.err.println(product.getId());
        // clear the session every 100 records
        if ((i % 100) == 0) {
            OBDal.getInstance().getSession().clear();
        }
        i++;
    }
}

From source file:org.openbravo.test.dal.DalPerformanceExampleTest.java

License:Open Source License

/**
 * Show explicit joining of referenced objects
 *///from ww  w. j a v  a2 s.  c o m
@Test
public void testJoinReferencedObjects() {
    setTestUserContext();
    {
        int i = 0;
        final OBQuery<BusinessPartner> bpQuery = OBDal.getInstance().createQuery(BusinessPartner.class, "");
        bpQuery.setMaxResult(1000);
        final ScrollableResults scroller = bpQuery.scroll(ScrollMode.FORWARD_ONLY);
        while (scroller.next()) {
            final BusinessPartner bp = (BusinessPartner) scroller.get()[0];

            // this will load the category object with a separate query
            System.err.println(bp.getBusinessPartnerCategory().getIdentifier());

            // clear the session every 100 records
            if ((i % 10) == 0) {
                OBDal.getInstance().getSession().clear();
            }
            i++;
        }
    }

    // start with an empty session
    OBDal.getInstance().getSession().clear();

    {
        int i = 0;
        // for joining referenced objects we can't use OBQuery, but have to
        // use a direct Hibernate query object
        final String queryStr = "from BusinessPartner as bp left join bp.businessPartnerCategory where bp.organization.id "
                + OBDal.getInstance().getReadableOrganizationsInClause();

        final Query qry = OBDal.getInstance().getSession().createQuery(queryStr);
        qry.setMaxResults(1000);
        final ScrollableResults scroller = qry.scroll(ScrollMode.FORWARD_ONLY);
        while (scroller.next()) {
            final BusinessPartner bp = (BusinessPartner) scroller.get()[0];

            // the category is already loaded, so this won't fire a query
            System.err.println(bp.getBusinessPartnerCategory().getIdentifier());

            // clear the session every 100 records
            if ((i % 100) == 0) {
                OBDal.getInstance().getSession().clear();
            }
            i++;
        }
    }
}

From source file:org.openbravo.test.dal.IssuesTest.java

License:Open Source License

@Test
  public void test20611() {
      OBCriteria<BusinessPartner> c = OBDal.getInstance().createCriteria(BusinessPartner.class);
      ScrollableResults iterator = c.scroll(ScrollMode.FORWARD_ONLY);
      Assert.assertTrue(iterator.next());
  }/*  w w w . jav  a  2 s .  co m*/

From source file:org.openhie.openempi.blocking.basicblockinghp.dao.hibernate.BlockingDaoHibernate.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
public Record loadRecord(final long recordId, final List<String> fieldNameSet) {
    final String[] fieldNames = fieldNameSet.toArray(new String[] {});
    return (Record) getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) {
            try {
                org.hibernate.Criteria criteria = createQueryFromFields(session, fieldNameSet);
                criteria.add(Restrictions.eq("personId", new Integer((int) recordId)));
                criteria.setCacheMode(CacheMode.IGNORE);
                criteria.setFetchSize(10000);
                ScrollableResults iterator = criteria.scroll(ScrollMode.FORWARD_ONLY);
                int count = 0;
                Record record = null;//from www  .j  av a 2s . c o m
                while (iterator.next()) {
                    Object[] values = iterator.get();
                    Person person = populatePersonObject(fieldNames, values);
                    Long recordId = person.getPersonId().longValue();
                    record = new Record(person);
                    record.setRecordId(recordId);
                    log.trace("Loaded " + count + " records with id " + recordId + " into the cache.");
                    count++;
                }
                return record;
            } catch (Exception e) {
                log.error("Failed while scrolling through the records: " + e, e);
                throw new RuntimeException("Failed while scrolling through the records: " + e.getMessage());
            }
        }
    });
}

From source file:org.openhie.openempi.blocking.basicblockinghp.dao.hibernate.BlockingDaoHibernate.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
public void loadAllRecords(final Cache recordCache, final List<String> fieldNameSet) {
    final String[] fieldNames = fieldNameSet.toArray(new String[] {});
    //      final String queryStr = buildQuery(fieldNames).toString();
    getHibernateTemplate().execute(new HibernateCallback() {
        @Override//from  w  w  w.j  a  v a2  s.c  o m
        public Object doInHibernate(Session session) {
            try {
                org.hibernate.Criteria criteria = createQueryFromFields(session, fieldNameSet);
                criteria.setCacheMode(CacheMode.IGNORE);
                criteria.setFetchSize(10000);
                ScrollableResults iterator = criteria.scroll(ScrollMode.FORWARD_ONLY);
                //               Query query = session.createQuery(queryStr);
                //               query.setCacheMode(CacheMode.IGNORE);
                //               query.setFetchSize(10000);
                //               ScrollableResults iterator = query.scroll(ScrollMode.FORWARD_ONLY);
                int count = 0;
                while (iterator.next()) {
                    Object[] values = iterator.get();
                    Person person = populatePersonObject(fieldNames, values);
                    Record record = new Record(person);
                    Long recordId = person.getPersonId().longValue();
                    record.setRecordId(recordId);
                    Element element = new Element(recordId, record);
                    recordCache.put(element);
                    log.trace("Loaded record " + recordId + " into the cache.");
                    count++;
                }
                log.debug("Loaded " + count + " records into the cache.");
            } catch (Exception e) {
                log.error("Failed while scrolling through the records: " + e, e);
            }
            return null;
        }
    });
}

From source file:org.openmrs.api.db.hibernate.HibernateContextDAO.java

License:Mozilla Public License

@Override
public void updateSearchIndexForType(Class<?> type) {
    //From http://docs.jboss.org/hibernate/search/3.3/reference/en-US/html/manual-index-changes.html#search-batchindex-flushtoindexes
    FullTextSession session = Search.getFullTextSession(sessionFactory.getCurrentSession());
    session.purgeAll(type);//from ww w  . ja v  a  2s  .c o  m

    //Prepare session for batch work
    session.flush();
    session.clear();

    FlushMode flushMode = session.getFlushMode();
    CacheMode cacheMode = session.getCacheMode();
    try {
        session.setFlushMode(FlushMode.MANUAL);
        session.setCacheMode(CacheMode.IGNORE);

        //Scrollable results will avoid loading too many objects in memory
        ScrollableResults results = session.createCriteria(type).setFetchSize(1000)
                .scroll(ScrollMode.FORWARD_ONLY);
        int index = 0;
        while (results.next()) {
            index++;
            session.index(results.get(0)); //index each element
            if (index % 1000 == 0) {
                session.flushToIndexes(); //apply changes to indexes
                session.clear(); //free memory since the queue is processed
            }
        }
        session.flushToIndexes();
        session.clear();
    } finally {
        session.setFlushMode(flushMode);
        session.setCacheMode(cacheMode);
    }
}

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. j  a va  2s.c  o  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)
 *///from w w w  . j av a2 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.amrsreports.db.hibernate.MohHibernateCoreDAO.java

License:Open Source License

@Override
public List<Object> executeScrollingHqlQuery(String query, Map<String, Object> substitutions) {
    Query q = sessionFactory.getCurrentSession().createQuery(query);

    applySubstitutions(q, substitutions);

    // optimizations go here
    q.setFetchSize(Integer.MIN_VALUE);
    q.setReadOnly(true);/*  w  w w . ja va 2 s. com*/

    List<Object> res = new ArrayList<Object>();

    long i = 0;

    ScrollableResults sr = q.scroll(ScrollMode.FORWARD_ONLY);
    while (sr.next()) {

        // rows always come back as an array
        Object[] o = sr.get();

        // but if there is only one object in the row, add it instead of the array
        if (o.length == 1)
            res.add(o[0]);
        else
            res.add(o);

        if (++i % 500 == 0)
            log.warn("processed #" + i);
    }

    log.warn("done. processed " + i + " total rows.");

    sr.close();

    return res;
}