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:com.hmsinc.epicenter.tools.reclassifier.Reclassifier.java

License:Open Source License

@Transactional
public void run() {

    setup();/*from   w  ww . jav a 2  s. c  om*/

    final String destinationTable = (arguments.length > 4) ? arguments[4] : DEFAULT_TABLE_NAME;
    final String query = new StringBuilder("INSERT INTO ").append(destinationTable)
            .append(INSERT_CLASSIFICATION).toString();

    final BatchSqlUpdate updater = new BatchSqlUpdate(modelDataSource, query);
    updater.declareParameter(new SqlParameter(Types.BIGINT));
    updater.declareParameter(new SqlParameter(Types.BIGINT));
    updater.setBatchSize(BATCH_SIZE);
    updater.compile();

    final StatelessSession ss = ((Session) entityManager.getDelegate()).getSessionFactory()
            .openStatelessSession();

    final Criteria c = ss.createCriteria(target.getInteractionClass())
            .add(Restrictions.eq("patientClass", target.getPatientClass())).addOrder(Order.asc("id"))
            .setCacheable(false);

    if (arguments.length > 2) {
        c.add(Restrictions.gt("id", Long.valueOf(arguments[2])));
    }

    if (arguments.length > 3) {
        c.add(Restrictions.lt("id", Long.valueOf(arguments[3])));
    }

    final ScrollableResults sr = c.scroll(ScrollMode.FORWARD_ONLY);
    int i = 0;
    while (sr.next()) {

        final Interaction interaction = (Interaction) sr.get(0);
        final Set<Classification> classifications = classificationService.classify(interaction, target);

        save(interaction, classifications, updater);

        i++;
        if (i % BATCH_SIZE == 0) {
            logger.info("Processed {} interactions (current id: {})", i, interaction.getId());
        }

        ((Session) entityManager.getDelegate()).evict(interaction);
    }

    sr.close();

    updater.flush();
}

From source file:com.reignite.query.StructuredQuery.java

License:Open Source License

private int runQuery(Criteria criteria, QueryResult result, int maxResults) {
    ScrollableResults scroll = criteria.scroll(ScrollMode.FORWARD_ONLY);
    int count = 0;
    if (scroll.setRowNumber(startIndex)) {
        while (count < maxResults) {
            Object[] row = scroll.get();
            count = fillResult(result, row) ? count += 1 : count;
            if (!scroll.next()) {
                break;
            }//from  w  ww .ja v  a 2s. c  om
        }
    }
    int totalResultCount = 0;
    if (scroll.last()) {
        totalResultCount = scroll.getRowNumber() + 1;
    }
    result.setTotalResults(totalResultCount);
    scroll.close();
    return count;
}

From source file:com.yahoo.elide.datastores.hibernate3.HibernateTransaction.java

License:Apache License

/**
 * Generates the Hibernate ScrollableIterator for Hibernate Query.
 *
 * @param loadClass The hibernate class to build the query off of.
 * @param criteria The criteria to use for filters
 * @param sortingRules The possibly empty sorting rules.
 * @param pagination The Optional pagination object.
 * @return The Iterable for Hibernate.//w  w  w .j  a  v a2  s  . c o m
 */
public Iterable loadObjects(final Class<?> loadClass, final Criteria criteria,
        final Optional<Set<Order>> sortingRules, final Optional<Pagination> pagination, RequestScope scope) {
    if (sortingRules.isPresent()) {
        sortingRules.get().forEach(criteria::addOrder);
    }

    if (pagination.isPresent()) {
        Pagination paginationData = pagination.get();
        criteria.setFirstResult(paginationData.getOffset());
        criteria.setMaxResults(paginationData.getLimit());
    } else {
        Integer queryLimit = getQueryLimit();
        if (queryLimit != null) {
            criteria.setMaxResults(queryLimit);
        }
    }

    if (isJoinQuery()) {
        joinCriteria(criteria, loadClass, scope);
    }

    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    if (!isScrollEnabled || isJoinQuery()) {
        return criteria.list();
    }
    return new ScrollableIterator(criteria.scroll(scrollMode));
}

From source file:com.yahoo.elide.datastores.hibernate5.HibernateTransaction.java

License:Apache License

/**
 * Generates the Hibernate ScrollableIterator for Hibernate Query.
 *
 * @param loadClass The hibernate class to build the query off of.
 * @param criteria The criteria to use for filters
 * @param sortingRules The possibly empty sorting rules.
 * @param pagination The Optional pagination object.
 * @return The Iterable for Hibernate.//from   ww w.  ja  va 2  s  .  c  om
 */
public Iterable loadObjects(final Class<?> loadClass, final Criteria criteria,
        final Optional<Set<Order>> sortingRules, final Optional<Pagination> pagination) {
    if (sortingRules.isPresent()) {
        sortingRules.get().forEach(criteria::addOrder);
    }

    if (pagination.isPresent()) {
        Pagination paginationData = pagination.get();
        criteria.setFirstResult(paginationData.getOffset());
        criteria.setMaxResults(paginationData.getLimit());
    }

    if (isScrollEnabled) {
        return new ScrollableIterator(criteria.scroll(scrollMode));
    }
    return criteria.list();
}

From source file:debop4k.data.orm.hibernate.dao.HibernateDao.java

License:Apache License

public ScrollableResults scroll(@NonNull Criteria criteria, ScrollMode scrollMode) {
    return criteria.scroll(scrollMode);
}

From source file:eu.interedition.text.util.SQL.java

License:Apache License

public static <T> Iterable<T> iterate(final Criteria c, Class<T> type) {
    return new Iterable<T>() {
        @Override//from ww w.  ja v  a 2s  .c  o  m
        public Iterator<T> iterator() {
            return new AbstractIterator<T>() {

                final ScrollableResults results = c.scroll(ScrollMode.FORWARD_ONLY);

                @Override
                @SuppressWarnings("unchecked")
                protected T computeNext() {
                    return (results.next() ? (T) results.get()[0] : endOfData());
                }
            };
        }
    };
}

From source file:fr.gael.dhus.database.dao.KeyStoreEntryDao.java

License:Open Source License

/**
 * Retrieves entries of a keyStore, oldest first.
 * @param keyStoreName the name of the keyStore
 * @return a ScrollableResult of entries
 *///  ww  w .j  a v a  2  s.c  o m
public ScrollableResults readOldestEntries(final String keyStoreName) {
    return getHibernateTemplate().execute(new HibernateCallback<ScrollableResults>() {
        @Override
        public ScrollableResults doInHibernate(Session session) throws HibernateException, SQLException {
            Criteria criteria = session.createCriteria(entityClass);
            criteria.add(Restrictions.eq("key.keyStore", keyStoreName));
            criteria.addOrder(Order.asc("insertionDate"));
            return criteria.scroll(ScrollMode.FORWARD_ONLY);
        }
    });
}

From source file:kr.debop4j.data.hibernate.repository.impl.HibernateDao.java

License:Apache License

@Override
public ScrollableResults getScroll(Criteria criteria, ScrollMode scrollMode) {
    return criteria.scroll(scrollMode);
}

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

License:Open Source License

/**
 * Execute a batch callback against a StatelessSession using a named query.
 * /*from  ww w. ja v  a 2  s  . 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.
 * /*from   w  w  w .ja  va2  s. com*/
 * @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;
        }
    });
}