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.candlepin.model.DetachedCandlepinQuery.java

License:Open Source License

/**
 * {@inheritDoc}//from  w w w  .  j  av  a 2 s  . com
 */
@Override
public ResultIterator<T> iterate(int column, boolean evict) {
    Criteria executable = this.getExecutableCriteria();

    // We always override the cache mode here to ensure we don't evict things that may be in
    // cache from another request.
    if (evict) {
        executable.setCacheMode(CacheMode.GET);
    }

    ScrollableResults cursor = executable.scroll(ScrollMode.FORWARD_ONLY);
    return new ColumnarResultIterator<>(this.session, cursor, column, evict);
}

From source file:org.candlepin.model.DetachedCandlepinQuery.java

License:Open Source License

/**
 * {@inheritDoc}/*from   w  ww .  j a v  a2s . com*/
 */
@Override
public ResultIterator<Object[]> iterateByRow() {
    Criteria executable = this.getExecutableCriteria();

    ScrollableResults cursor = executable.scroll(ScrollMode.FORWARD_ONLY);
    return new RowResultIterator(cursor);
}

From source file:org.candlepin.model.RowResultIteratorTest.java

License:Open Source License

@Test
public void testHasNextWithElements() {
    this.ownerCurator.create(TestUtil.createOwner());
    Query query = this.session.createQuery("SELECT o FROM Owner o");

    RowResultIterator iterator = new RowResultIterator(query.scroll(ScrollMode.FORWARD_ONLY));

    try {// w w w.ja  va  2 s. c o m
        assertTrue(iterator.hasNext());
    } finally {
        iterator.close();
    }
}

From source file:org.candlepin.model.RowResultIteratorTest.java

License:Open Source License

@Test
public void testHasNextWithoutElements() {
    Query query = this.session.createQuery("SELECT o FROM Owner o");

    RowResultIterator iterator = new RowResultIterator(query.scroll(ScrollMode.FORWARD_ONLY));

    try {/*from  www .ja  va2s  . com*/
        assertFalse(iterator.hasNext());
    } finally {
        iterator.close();
    }
}

From source file:org.candlepin.model.RowResultIteratorTest.java

License:Open Source License

@Test
public void testNextWithElements() {
    Owner owner1 = TestUtil.createOwner();
    Owner owner2 = TestUtil.createOwner();
    Owner owner3 = TestUtil.createOwner();
    this.ownerCurator.create(owner1);
    this.ownerCurator.create(owner2);
    this.ownerCurator.create(owner3);

    Query query = this.session.createQuery("SELECT o FROM Owner o");

    RowResultIterator iterator = new RowResultIterator(query.scroll(ScrollMode.FORWARD_ONLY));

    try {//from www.j  av a  2s.  co  m
        List<Owner> owners = new LinkedList<>();

        // Note: Since we're testing everything in isolation here, we can't
        // be expecting .hasNext to be functional here. :)
        owners.add((Owner) iterator.next()[0]);
        owners.add((Owner) iterator.next()[0]);
        owners.add((Owner) iterator.next()[0]);

        assertTrue(owners.contains(owner1));
        assertTrue(owners.contains(owner2));
        assertTrue(owners.contains(owner3));
    } finally {
        iterator.close();
    }
}

From source file:org.candlepin.model.RowResultIteratorTest.java

License:Open Source License

@Test(expected = NoSuchElementException.class)
public void testNextWithoutElements() {
    Query query = this.session.createQuery("SELECT o FROM Owner o");

    RowResultIterator iterator = new RowResultIterator(query.scroll(ScrollMode.FORWARD_ONLY));

    try {//from  w ww.ja v a 2s. co  m
        iterator.next(); // Kaboom
    } finally {
        iterator.close();
    }
}

From source file:org.candlepin.model.RowResultIteratorTest.java

License:Open Source License

@Test(expected = UnsupportedOperationException.class)
public void testRemoveAlwaysFails() {
    this.ownerCurator.create(TestUtil.createOwner());
    Query query = this.session.createQuery("SELECT o FROM Owner o");

    RowResultIterator iterator = new RowResultIterator(query.scroll(ScrollMode.FORWARD_ONLY));

    try {//w w w.  ja  v  a  2s . c om
        iterator.next();
        iterator.remove();
    } finally {
        iterator.close();
    }
}

From source file:org.codehaus.grepo.query.hibernate.executor.ExecutorRepositoryTest.java

License:Apache License

/**
 * Tests the "scroll" executor./*  w ww . ja  v a  2 s. com*/
 */
@Test
public void testScrollExecutor() {
    ScrollableResults sr = repo.scrollByUsername("username");
    Assert.assertTrue(sr.next());

    sr = repo.scrollByUsernameWithStaticScrollMode("username");
    Assert.assertTrue(sr.next());

    sr = repo.scrollByUsernameWithDynamicScrollMode1("username", HibernateScrollMode.FORWARD_ONLY);
    Assert.assertTrue(sr.next());

    sr = repo.scrollByUsernameWithDynamicScrollMode2("username", ScrollMode.FORWARD_ONLY);
    Assert.assertTrue(sr.next());
}

From source file:org.compass.gps.device.hibernate.indexer.ScrollableHibernateIndexEntitiesIndexer.java

License:Apache License

public void performIndex(CompassSession session, IndexEntity[] entities) {
    for (IndexEntity entity : entities) {
        EntityInformation entityInformation = (EntityInformation) entity;
        if (device.isFilteredForIndex(entityInformation.getName())) {
            continue;
        }//w w w .  j a va2s. c om
        if (!device.isRunning()) {
            return;
        }
        ScrollableResults cursor = null;
        Session hibernateSession = device.getSessionFactory().openSession();
        hibernateSession.setCacheMode(CacheMode.IGNORE);
        Transaction hibernateTransaction = null;
        try {
            hibernateTransaction = hibernateSession.beginTransaction();
            if (log.isDebugEnabled()) {
                log.debug(device.buildMessage("Indexing entities [" + entityInformation.getName()
                        + "] using query [" + entityInformation.getQueryProvider() + "]"));
            }

            Criteria criteria = entityInformation.getQueryProvider().createCriteria(hibernateSession,
                    entityInformation);
            if (criteria != null) {
                if (performOrderById) {
                    Boolean performOrder = performOrderByPerEntity.get(entityInformation.getName());
                    if (performOrder == null || performOrder) {
                        ClassMetadata metadata = hibernateSession.getSessionFactory()
                                .getClassMetadata(entityInformation.getName());
                        String idPropName = metadata.getIdentifierPropertyName();
                        if (idPropName != null) {
                            criteria.addOrder(Order.asc(idPropName));
                        }
                    }
                }
                criteria.setFetchSize(device.getFetchCount());
                cursor = criteria.scroll(ScrollMode.FORWARD_ONLY);
            } else {
                Query query = entityInformation.getQueryProvider().createQuery(hibernateSession,
                        entityInformation);
                cursor = query.scroll(ScrollMode.FORWARD_ONLY);
            }

            // store things in row buffer to allow using batch fetching in Hibernate
            RowBuffer buffer = new RowBuffer(session, hibernateSession, device.getFetchCount());
            Object prev = null;
            while (true) {
                try {
                    if (!cursor.next()) {
                        break;
                    }
                } catch (ObjectNotFoundException e) {
                    continue;
                }
                Object item = cursor.get(0);
                if (prev != null && item != prev) {
                    buffer.put(prev);
                }
                prev = item;
                if (buffer.shouldFlush()) {
                    // put also the item/prev since we are clearing the session
                    // in the flush process
                    buffer.put(prev);
                    buffer.flush();
                    prev = null;
                }
            }
            if (prev != null) {
                buffer.put(prev);
            }
            buffer.close();
            cursor.close();

            hibernateTransaction.commit();
        } catch (Exception e) {
            log.error(device.buildMessage("Failed to index the database"), e);
            if (cursor != null) {
                try {
                    cursor.close();
                } catch (Exception e1) {
                    log.warn(device.buildMessage("Failed to close cursor on error, ignoring"), e1);
                }
            }
            if (hibernateTransaction != null) {
                try {
                    hibernateTransaction.rollback();
                } catch (Exception e1) {
                    log.warn("Failed to rollback Hibernate", e1);
                }
            }
            if (!(e instanceof HibernateGpsDeviceException)) {
                throw new HibernateGpsDeviceException(device.buildMessage("Failed to index the database"), e);
            }
            throw (HibernateGpsDeviceException) e;
        } finally {
            hibernateSession.close();
            session.close();
        }
    }
}

From source file:org.compass.gps.device.hibernate.scrollable.Hibernate3ScrollableResultsGpsDevice.java

License:Apache License

/**
 * Indexes the data/*ww  w.  ja v a 2 s .  co  m*/
 */
protected void doIndex(CompassSession session) throws CompassException {
    // reset the snapshot data before we perform the index operation
    snapshot = new HibernateSnapshot();
    for (Iterator it = mappings.iterator(); it.hasNext();) {
        ResultSetToResourceMapping mapping = (ResultSetToResourceMapping) it.next();
        if (mapping.supportsVersioning()) {
            HibernateAliasSnapshot aliasSnapshot = new HibernateAliasSnapshot(mapping.getAlias());
            snapshot.putAliasSnapshot(aliasSnapshot);
        }
    }

    if (log.isInfoEnabled()) {
        log.info(buildMessage("Indexing the database with fetch count [" + fetchCount + "]"));
    }

    IndexExecution[] indexExecutions = doGetIndexExecutions();
    for (int i = 0; i != indexExecutions.length; i++) {
        IndexExecution indexExecution = indexExecutions[i];

        HibernateSessionWrapper sessionWrapper = doGetHibernateSessionWrapper();

        try {
            sessionWrapper.open();

            Session hibernateSession = ((Hibernate3SessionWrapper) sessionWrapper).getSession();

            String queryString = indexExecution.getStatementQuery();

            if (log.isDebugEnabled()) {
                log.debug("queryString: " + queryString);
            }

            Query query = hibernateSession.createQuery(queryString).setCacheMode(CacheMode.IGNORE);
            String[] returnAliases = query.getReturnAliases();

            ScrollableResults rs = query.scroll(ScrollMode.FORWARD_ONLY);
            int count = 0;
            while (rs.next()) {
                processRow(indexExecution.getDescription(), rs, returnAliases, session);
                if (++count % fetchCount == 0) {
                    // release memory
                    hibernateSession.flush();
                    hibernateSession.clear();
                }
            }
            rs.close();

        } catch (Exception e) {
            log.error(buildMessage("Failed to index the database"), e);
            sessionWrapper.closeOnError();
            if (!(e instanceof HibernateGpsDeviceException)) {
                throw new HibernateGpsDeviceException(buildMessage("Failed to index the database"), e);
            }
            throw (HibernateGpsDeviceException) e;
        }

    }

    if (log.isInfoEnabled()) {
        log.info(buildMessage("Finished indexing the database"));
    }

    // save the sanpshot data
    getSnapshotPersister().save(snapshot);
}