Example usage for org.hibernate ScrollableResults get

List of usage examples for org.hibernate ScrollableResults get

Introduction

In this page you can find the example usage for org.hibernate ScrollableResults get.

Prototype

Object get(int i);

Source Link

Document

Get the ith object in the current row of results, without initializing any other results in the row.

Usage

From source file:kr.debop4j.search.dao.HibernateSearchDao.java

License:Apache License

@Override
public void indexAll(Class<?> clazz, int batchSize) {
    if (log.isDebugEnabled())
        log.debug("[{}]?  ?  ??? ...", clazz);

    clearIndex(clazz);//from w  ww.j a v  a2  s. c o m

    if (batchSize < BATCH_SIZE)
        batchSize = BATCH_SIZE;

    final FullTextSession fts = getFullTextSession();

    FlushMode currentFlushMode = fts.getFlushMode();
    CacheMode currentCacheMode = fts.getCacheMode();
    fts.setFlushMode(FlushMode.MANUAL);
    fts.setCacheMode(CacheMode.IGNORE);

    try {
        Transaction tx = fts.beginTransaction();
        ScrollableResults results = fts.createCriteria(clazz).scroll(ScrollMode.FORWARD_ONLY);
        int index = 0;
        while (results.next()) {
            index++;
            fts.index(results.get(0));
            if (index % batchSize == 0) {
                fts.flushToIndexes();
                fts.clear();
            }
        }
        fts.flushToIndexes();
        tx.commit();

        if (log.isDebugEnabled())
            log.debug("[{}]?   [{}]   ??? !!!",
                    clazz, index);
    } finally {
        fts.setFlushMode(currentFlushMode);
        fts.setCacheMode(currentCacheMode);
    }
}

From source file:magoffin.matt.dao.hbm.GenericHibernateDao.java

License:Open Source License

/**
 * Execute a batch callback using a named query.
 * /*from  www  .ja  va2s.  c o  m*/
 * @param queryName the named query name
 * @param parameters the named parameters to pass to the query
 * @param callback the callback
 * @return the number of items processed
 */
protected Integer executeNamedQueryBatchCallback(final String queryName, final Map<String, Object> parameters,
        final BatchCallback<T> callback) {
    return getHibernateTemplate().execute(new HibernateCallback<Integer>() {
        @SuppressWarnings("unchecked")
        @Override
        public Integer doInHibernate(Session session) throws HibernateException, SQLException {
            Query q = session.getNamedQuery(queryName);
            if (parameters != null) {
                for (String paramName : parameters.keySet()) {
                    q.setParameter(paramName, parameters.get(paramName));
                }
            }
            q.setCacheMode(CacheMode.IGNORE);
            ScrollableResults items = q.scroll(ScrollMode.FORWARD_ONLY);
            int count = 0;

            OUTER: while (items.next()) {
                T item = (T) items.get(0);
                BatchCallbackResult action = callback.handle(item);
                switch (action) {
                case DELETE:
                    session.delete(item);
                    break;

                case UPDATE:
                case UPDATE_STOP:
                    store(item);
                    if (action == BatchCallbackResult.UPDATE_STOP) {
                        break OUTER;
                    }
                    break;

                case STOP:
                    break OUTER;

                case CONTINUE:
                    // nothing to do
                    break;
                }
                if (++count % batchFlushCount == 0) {
                    session.flush();
                    session.clear();
                }
            }

            return count;
        }
    });
}

From source file:magoffin.matt.dao.hbm.GenericHibernateDao.java

License:Open Source License

/**
 * Execute a batch callback against a StatelessSession using a named query.
 * /*  w ww  . j av  a  2s . c om*/
 * <p>The DELETE, UPDATE, and UPDATE_STOP {@link BatchCallbackResult}
 * values are not supported in this operation, and will throw an 
 * <code>UnsupportedOperationException</code> if returned by the 
 * {@link BatchCallback} instance passed to this method.</p>
 * 
 * @param criteriaBuilder the criteria builder
 * @param callback the callback
 * @param options the options
 * @return the number of items processed
 */
@SuppressWarnings("unchecked")
protected Integer executeStatelessCriteriaBatchCallback(final CriteriaBuilder criteriaBuilder,
        final BatchCallback<T> callback, final BatchOptions options) {
    StatelessSession session = getHibernateTemplate().getSessionFactory().openStatelessSession();
    Transaction tx = session.beginTransaction();
    try {
        Criteria criteria = session.createCriteria(getType());
        criteria.setFetchSize(options.getBatchSize());
        criteriaBuilder.buildCriteria(criteria);
        ScrollableResults items = criteria.scroll(ScrollMode.FORWARD_ONLY);
        int count = 0;

        OUTER: while (items.next()) {
            T item = (T) items.get(0);
            BatchCallbackResult action = callback.handle(item);
            switch (action) {
            case DELETE:
            case UPDATE:
            case UPDATE_STOP:
                throw new UnsupportedOperationException("Action " + action + " not possible during "
                        + options.getMode() + " mode batch processing");

            case STOP:
                break OUTER;

            case CONTINUE:
                // nothing to do
                break;
            }
        }
        tx.commit();
        return count;
    } catch (RuntimeException e) {
        tx.rollback();
        throw e;
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

From source file:magoffin.matt.dao.hbm.GenericHibernateDao.java

License:Open Source License

/**
 * Execute a batch callback against a normal Hibernate Session using a named query.
 * /*w w  w .  j  av a2 s.  c  o m*/
 * @param criteriaBuilder the criteria builder
 * @param callback the callback
 * @param options the options
 * @return the number of items processed
 */
protected Integer executeLiveCriteriaBatchCallback(final CriteriaBuilder criteriaBuilder,
        final BatchCallback<T> callback, final BatchOptions options) {
    return getHibernateTemplate().execute(new HibernateCallback<Integer>() {
        @SuppressWarnings("unchecked")
        @Override
        public Integer doInHibernate(Session session) throws HibernateException, SQLException {
            Criteria criteria = session.createCriteria(type);
            criteria.setFetchSize(options.getBatchSize());
            criteriaBuilder.buildCriteria(criteria);
            ScrollableResults items = criteria.scroll(ScrollMode.FORWARD_ONLY);
            int count = 0;

            OUTER: while (items.next()) {
                T item = (T) items.get(0);
                BatchCallbackResult action = callback.handle(item);
                switch (action) {
                case DELETE:
                    session.delete(item);
                    break;

                case UPDATE:
                case UPDATE_STOP:
                    store(item);
                    if (action == BatchCallbackResult.UPDATE_STOP) {
                        break OUTER;
                    }
                    break;

                case STOP:
                    break OUTER;

                case CONTINUE:
                    // nothing to do
                    break;
                }
                if (++count % 20 == 0) {
                    session.flush();
                    session.clear();
                }
            }

            return count;
        }
    });
}

From source file:magoffin.matt.ma2.dao.hbm.HibernateAlbumDao.java

License:Open Source License

public int reassignAlbumsUsingTheme(final Theme oldTheme, final Theme newTheme) {
    return getHibernateTemplate().execute(new HibernateCallback<Integer>() {

        public Integer doInHibernate(Session session) throws HibernateException, SQLException {
            ScrollableResults albums = session.getNamedQuery(QUERY_ALBUMS_FOR_THEME_ID)
                    .setLong("themeId", oldTheme.getThemeId()).setCacheMode(CacheMode.IGNORE)
                    .scroll(ScrollMode.FORWARD_ONLY);
            int count = 0;
            while (albums.next()) {
                Album album = (Album) albums.get(0);
                album.setTheme(newTheme);
                if (++count % 20 == 0) {
                    session.flush();/*from w w  w .j  av  a  2  s .  co m*/
                    session.clear();
                }
            }
            return count;
        }
    });
}

From source file:mitm.common.hibernate.AbstractScrollableResultsIterator.java

License:Open Source License

protected Object get(ScrollableResults results) {
    return results.get(0);
}

From source file:mockit.emulation.hibernate3.QueryTest.java

License:Open Source License

@Test
public void findChildrenEntitiesWithGivenParentName() {
    addChildrenEntities();//ww w.  j a va 2  s.c  om
    QueryEmul query = new QueryEmul("select c from ChildEntity c where c.parent.name like ?", entities);
    query.setParameter(0, "%y%");

    ScrollableResults found = query.scroll();

    assertTrue(found.next());
    assertSame(child, found.get(0));
}

From source file:net.chrisrichardson.foodToGo.domain.hibernate.HibernateOrderRepositoryImpl.java

License:Apache License

private List getOrdersFromScrollableResults(ScrollableResults results1) {
    List orders = new ArrayList();
    int pageSize = 10;
    if (results1.first() && results1.scroll(0)) {
        for (int i = 0; i < pageSize; i++) {
            orders.add(results1.get(0));
            if (!results1.next())
                break;
        }//from w w w.ja  v  a 2  s. co  m
    }

    List results = orders;
    return results;
}

From source file:net.jforum.actions.LuceneAdminActions.java

License:Open Source License

public void rebuildIndex() {

    Runnable indexingJob = new Runnable() {
        public void run() {
            Session session = null;/*w  w  w  .  j  a v a2  s. co m*/

            try {
                session = sessionFactory.openSession();

                FullTextSession fullTextSession = Search.createFullTextSession(session);
                fullTextSession.setFlushMode(FlushMode.MANUAL);
                fullTextSession.setCacheMode(CacheMode.IGNORE);

                session.beginTransaction();

                int index = 0;
                int batchSize = config.getInt(ConfigKeys.LUCENE_BATCH_SIZE);

                ScrollableResults results = fullTextSession.createCriteria(Post.class).createAlias("topic", "t")
                        .scroll(ScrollMode.FORWARD_ONLY);

                while (results.next() && "1".equals(config.getValue(ConfigKeys.LUCENE_CURRENTLY_INDEXING))) {
                    index++;

                    fullTextSession.index(results.get(0));

                    if (index % batchSize == 0) {
                        session.clear();
                    }
                }

                session.getTransaction().commit();
            } catch (Exception e) {
                if (session.getTransaction().isActive()) {
                    session.getTransaction().rollback();
                }
            } finally {
                if (session.isOpen() && session.isConnected()) {
                    session.close();
                }
            }
        }
    };

    this.config.addProperty(ConfigKeys.LUCENE_CURRENTLY_INDEXING, "1");

    Thread thread = new Thread(indexingJob);
    thread.start();

    this.viewService.redirectToAction(Actions.LIST);
}

From source file:net.jforum.controllers.LuceneAdminController.java

License:Open Source License

public void rebuildIndex() {

    Runnable indexingJob = new Runnable() {
        public void run() {
            Session session = null;//from   w  w w.  j  a  v a2 s. co  m

            try {
                session = sessionFactory.openSession();

                FullTextSession fullTextSession = Search.createFullTextSession(session);
                fullTextSession.setFlushMode(FlushMode.MANUAL);
                fullTextSession.setCacheMode(CacheMode.IGNORE);

                session.beginTransaction();

                int index = 0;
                int batchSize = config.getInt(ConfigKeys.LUCENE_BATCH_SIZE);

                ScrollableResults results = fullTextSession.createCriteria(Post.class).createAlias("topic", "t")
                        .scroll(ScrollMode.FORWARD_ONLY);

                while (results.next() && "1".equals(config.getValue(ConfigKeys.LUCENE_CURRENTLY_INDEXING))) {
                    index++;

                    fullTextSession.index(results.get(0));

                    if (index % batchSize == 0) {
                        session.clear();
                    }
                }

                session.getTransaction().commit();
            } catch (Exception e) {
                if (session.getTransaction().isActive()) {
                    session.getTransaction().rollback();
                }
            } finally {
                if (session.isOpen() && session.isConnected()) {
                    session.close();
                }
            }
        }
    };

    this.config.addProperty(ConfigKeys.LUCENE_CURRENTLY_INDEXING, "1");

    Thread thread = new Thread(indexingJob);
    thread.start();

    this.result.redirectTo(this).list();
}