Example usage for org.hibernate Query scroll

List of usage examples for org.hibernate Query scroll

Introduction

In this page you can find the example usage for org.hibernate Query scroll.

Prototype

ScrollableResults scroll(ScrollMode scrollMode);

Source Link

Document

Return the query results as ScrollableResults.

Usage

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

License:Apache License

private void doCreateAndUpdateFor(final List snapshots,
        final CreateAndUpdateSnapshotEvent createAndUpdateSnapshotEvent, final boolean useCreate)
        throws HibernateGpsDeviceException {
    final ResultSetToResourceMapping mapping = createAndUpdateSnapshotEvent.getMapping();
    CompassGpsInterfaceDevice compassGps = createAndUpdateSnapshotEvent.getCompassGps();
    compassGps.executeForMirror(new CompassCallbackWithoutResult() {
        protected void doInCompassWithoutResult(CompassSession session) throws CompassException {
            String query = (String) createAndUpdateQueries.get(mapping.getAlias());

            try {
                Session s = createAndUpdateSnapshotEvent.getSession();
                Query hibernateQuery = s.createQuery(query);
                for (Iterator it = snapshots.iterator(); it.hasNext();) {
                    HibernateAliasRowSnapshot rowSnapshot = (HibernateAliasRowSnapshot) it.next();
                    Resource resource = session.createResource(mapping.getAlias());
                    Hibernate3ScrollableResultsRowMarshallHelper marshallHelper = new Hibernate3ScrollableResultsRowMarshallHelper(
                            mapping, session, resource);
                    //XXX: clearParameters of hibernateQuery?
                    List ids = rowSnapshot.getIds();
                    for (int i = 0; i < ids.size(); i++) {
                        Object idValue = ids.get(i);
                        hibernateQuery.setParameter(i, idValue);
                    }//from ww  w . j a  va  2s . c  o  m

                    String[] returnAliases = hibernateQuery.getReturnAliases();
                    ScrollableResults rs = hibernateQuery.scroll(ScrollMode.FORWARD_ONLY);
                    if (!rs.next()) {
                        // it was deleted between the calls, do nothing
                        continue;
                    }
                    rs.close();

                    marshallHelper.marshallResultSet(rs, returnAliases);
                    if (useCreate) {
                        session.create(resource);
                    } else {
                        session.save(resource);
                    }
                    session.evictAll();
                }
            } catch (Exception e) {
                throw new HibernateGpsDeviceException("Failed to execute query for create/update", e);
            } finally {
                //TODO: close Session?
                // maybe keeping Session in the events is not a good idea
                // -> keep the SessionWrapper in event?
                // or close session somewhere else
                //(session will also be closed on committing the transaction)
            }
        }
    });
}

From source file:org.easybatch.extensions.hibernate.HibernateRecordReader.java

License:Open Source License

@Override
public void open() {
    currentRecordNumber = 0;//w  w w . ja  v a  2  s.  c om
    Query hibernateQuery = session.createQuery(query);
    hibernateQuery.setReadOnly(true);
    if (maxResults >= 1) {
        hibernateQuery.setMaxResults(maxResults);
    }
    if (fetchSize >= 1) {
        hibernateQuery.setFetchSize(fetchSize);
    }
    scrollableResults = hibernateQuery.scroll(ScrollMode.FORWARD_ONLY);
}

From source file:org.eclipse.emf.cdo.server.internal.hibernate.HibernateQueryHandler.java

License:Open Source License

/**
 * Executes hql queries. Gets the session from the {@link HibernateStoreAccessor} creates a hibernate query and sets
 * the parameters taken from the {@link CDOQueryInfo#getParameters()}. Takes into account the
 * {@link CDOQueryInfo#getMaxResults()} and the {@link IHibernateStore#FIRST_RESULT} values for paging.
 *
 * @param info/*from w  ww  . j a  v a  2s .c  o  m*/
 *          the object containing the query and parameters
 * @param context
 *          the query results are placed in the context
 * @see IQueryHandler#executeQuery(CDOQueryInfo, IQueryContext)
 */
public void executeQuery(CDOQueryInfo info, IQueryContext context) {
    // get a transaction, the hibernateStoreAccessor is placed in a threadlocal
    // so all db access uses the same session.
    final Session session = hibernateStoreAccessor.getHibernateSession();
    try {
        // create the query
        final Query query = session.createQuery(info.getQueryString());
        query.setReadOnly(true);

        // get the parameters with some parameter conversion
        int firstResult = -1;
        boolean cacheResults = true;
        for (String key : info.getParameters().keySet()) {
            if (key.compareToIgnoreCase(IHibernateStore.CACHE_RESULTS) == 0) {
                try {
                    cacheResults = (Boolean) info.getParameters().get(key);
                } catch (ClassCastException e) {
                    throw new IllegalArgumentException("Parameter " + IHibernateStore.CACHE_RESULTS //$NON-NLS-1$
                            + " must be a boolean. errorMessage " + e.getMessage());
                }
            } else if (key.compareToIgnoreCase(IHibernateStore.FIRST_RESULT) == 0) {
                final Object o = info.getParameters().get(key);
                if (o != null) {
                    try {
                        firstResult = (Integer) o;
                    } catch (ClassCastException e) {
                        throw new IllegalArgumentException(
                                "Parameter firstResult must be an integer but it is a " + o //$NON-NLS-1$
                                        + " class " + o.getClass().getName()); //$NON-NLS-1$
                    }
                }
            } else {
                // in case the parameter is a CDOID get the object from the db
                final Object param = info.getParameters().get(key);
                if (param instanceof CDOID && HibernateUtil.getInstance().isStoreCreatedID((CDOID) param)) {
                    final CDOID id = (CDOID) param;
                    final String entityName = HibernateUtil.getInstance().getEntityName(id);
                    final Serializable idValue = HibernateUtil.getInstance().getIdValue(id);
                    final CDORevision revision = (CDORevision) session.get(entityName, idValue);
                    query.setEntity(key, revision);
                    if (cacheResults) {
                        addToRevisionCache(revision);
                    }
                } else {
                    query.setParameter(key, param);
                }
            }
        }

        // set the first result
        if (firstResult > -1) {
            query.setFirstResult(firstResult);
        }

        // the max result
        if (info.getMaxResults() != CDOQueryInfo.UNLIMITED_RESULTS) {
            query.setMaxResults(info.getMaxResults());
        }

        final ScrollableResults scroller = query.scroll(ScrollMode.FORWARD_ONLY);

        // and go for the query
        // future extension: support iterate, scroll through a parameter
        int i = 0;
        try {
            while (scroller.next()) {
                Object[] os = scroller.get();
                Object o;
                if (os.length == 1) {
                    o = handleAuditEntries(os[0]);
                } else {
                    o = handleAuditEntries(os);
                }

                final boolean addOneMore = context.addResult(o);
                if (cacheResults && o instanceof CDORevision) {
                    addToRevisionCache((CDORevision) o);
                }
                if (o instanceof InternalCDORevision) {
                    ((InternalCDORevision) o).freeze();
                }

                // clear the session every 1000 results or so
                if (i++ % 1000 == 0) {
                    session.clear();
                }

                if (!addOneMore) {
                    return;
                }
            }
        } finally {
            scroller.close();
        }
    } finally {
        session.close();
    }
}

From source file:org.eclipse.emf.cdo.server.internal.hibernate.HibernateStoreAccessor.java

License:Open Source License

public void queryXRefs(QueryXRefsContext context) {
    final Session session = getHibernateSession();
    for (CDOID targetCdoId : context.getTargetObjects().keySet()) {
        final CDORevision revision = HibernateUtil.getInstance().getCDORevision(targetCdoId);
        final EClass targetEClass = context.getTargetObjects().get(targetCdoId);

        if (!getStore().isMapped(targetEClass)) {
            continue;
        }//from w ww. j  a va  2  s .c om

        final String targetEntityName = getStore().getEntityName(targetEClass);
        final Map<EClass, List<EReference>> sourceCandidates = context.getSourceCandidates();
        for (EClass sourceEClass : sourceCandidates.keySet()) {

            if (!getStore().isMapped(sourceEClass)) {
                continue;
            }

            final String sourceEntityName = getStore().getEntityName(sourceEClass);
            for (EReference eref : sourceCandidates.get(sourceEClass)) {
                // handle transient ereferences
                if (!isEReferenceMapped(session, sourceEntityName, eref)) {
                    continue;
                }

                final String hql;
                if (eref.isMany()) {
                    hql = "select ref from " + sourceEntityName + " as ref, " + targetEntityName
                            + " as refTo where refTo = :to and refTo in elements(ref." + eref.getName() + ")";
                } else {
                    hql = "select ref from " + sourceEntityName + " as ref where :to = ref." + eref.getName();
                }

                final Query qry = session.createQuery(hql);
                qry.setEntity("to", revision);
                ScrollableResults result = qry.scroll(ScrollMode.FORWARD_ONLY);
                while (result.next()) {
                    final InternalCDORevision sourceRevision = (InternalCDORevision) result.get()[0];

                    sourceRevision.freeze();

                    int sourceIndex = 0;
                    if (eref.isMany()) {
                        // note this takes performance for sure as the list is read,
                        // consider not supporting sourceIndex, or doing it differently
                        final WrappedHibernateList cdoList = (WrappedHibernateList) sourceRevision
                                .getList(eref);
                        sourceIndex = cdoList.getDelegate().indexOf(revision);
                    }

                    boolean more = context.addXRef(targetCdoId, sourceRevision.getID(), eref, sourceIndex);
                    if (!more) {
                        return;
                    }
                }
            }
        }
    }
}

From source file:org.eurekastreams.commons.search.bootstrap.SearchIndexManager.java

License:Apache License

/**
 * Purge & index all entities with the input class and name.
 *
 * @param entityClass//from  w  w w.  j a  v a 2 s.c om
 *            the type of entities to reindex into search index.
 *
 * @param entityName
 *            the name of the entity to reindex
 *
 * @param search
 *            the FullTextSession to use
 */
@SuppressWarnings("unchecked")
public void reindexEntities(final Class entityClass, final String entityName, final FullTextSession search) {
    log.info("reindexEntities(" + entityClass.toString() + ", " + entityName + ")");

    // purge first
    purgeSearchIndex(entityClass, search);

    log.info("Creating query to find batches of " + entityName);
    Query q = search.createQuery("FROM " + entityName)
            // set the result transformer
            //        .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY) <TODO COMMENTED OUT>
            // minimize cache
            .setCacheMode(CacheMode.IGNORE)
            // limit fetch size
            .setFetchSize(fetchBatchSize);
    log.info("setting scroll mode to FORWARD_ONLY for " + entityName);
    ScrollableResults scroll = q.scroll(ScrollMode.FORWARD_ONLY);

    int batch = 0;
    while (scroll.next()) {
        batch++;
        search.index(scroll.get(0));
        if (batch % flushBatchSize == 0) {
            if (log.isInfoEnabled()) {
                log.info("Flushing " + entityName + " - " + batch);
            }

            // no need to call s.flush()
            // we don't change anything
            search.flushToIndexes();
            search.clear();
        }
    }

    log.info("Flushing " + entityName + " - " + batch + " (final)");
    search.flushToIndexes();
    search.clear();

    log.info("Optimizing index for " + entityName);
    search.getSearchFactory().optimize(entityClass);
}

From source file:org.gbif.portal.dao.DAOUtils.java

License:Open Source License

/**
 * Process results, scrolling through each record in turn only loading that specific record.
 * //  ww w  .j  a  v a 2 s. c  o  m
 * @param resultsOutputter
 * @param session
 * @param query
 * @param associationTraverser
 * @param batchSize
 * @throws IOException
 */
public static void scrollResults(final ResultsOutputter resultsOutputter, Session session, Query query,
        AssociationTraverser associationTraverser, int batchSize) throws IOException {
    query.setReadOnly(true);
    query.setFetchSize(batchSize);

    //Using scrollable results to prevent initiation of all model objects
    ScrollableResults sr = query.scroll(ScrollMode.FORWARD_ONLY);

    //go to beginning of resultset
    boolean isNotEmpty = sr.first();
    if (!isNotEmpty) {
        //this is necessary due to a bug with ScrollableResults
        //allowing continuous scrolling over an empty resultset. genius.
        return;
    }

    //iterate through the results
    processScrollableResults(resultsOutputter, session, sr, associationTraverser, batchSize);

    //check for a chain
    if (resultsOutputter instanceof ChainableResultsOutputter) {
        ChainableResultsOutputter cro = (ChainableResultsOutputter) resultsOutputter;
        ResultsOutputter nextResultsOutputter = cro.getNextResultsOutputter();
        while (nextResultsOutputter != null && !cro.isChainInOnePass()) {
            //back to the start
            sr.first();
            processScrollableResults(nextResultsOutputter, session, sr, associationTraverser, batchSize);
            if (resultsOutputter instanceof ChainableResultsOutputter) {
                cro = (ChainableResultsOutputter) resultsOutputter;
                if (!cro.isChainInOnePass())
                    nextResultsOutputter = cro.getNextResultsOutputter();
                else
                    nextResultsOutputter = null;
            } else {
                nextResultsOutputter = null;
            }
        }
    }
    if (associationTraverser != null)
        associationTraverser.reset();
    //close the results set
    sr.close();
}

From source file:org.jasig.ssp.dao.DirectoryPersonSearchDao.java

License:Apache License

public void exportableSearch(CaseloadCsvWriterHelper csvWriterHelper, PersonSearchRequest personSearchRequest)
        throws IOException {

    StatelessSession openStatelessSession = null;

    try {//from   w w w. j ava 2 s.c o  m
        openStatelessSession = sessionFactory.openStatelessSession();
        Pair<Long, Query> querySet = prepSearchQuery(openStatelessSession, personSearchRequest);

        querySet.getSecond().setResultTransformer(
                new NamespacedAliasToBeanResultTransformer(PersonSearchResult2.class, "person_"));
        Query query = querySet.getSecond().setFetchSize(10).setReadOnly(true);
        ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY);

        csvWriterHelper.write(results, -1L);
    } finally {
        if (openStatelessSession != null) {
            try {
                openStatelessSession.close();
            } catch (Exception e) {
                // nothing to do and likely harmless
                LOGGER.info("Failed to close Hibernate StatelessSession", e);
            }
        }
    }

}

From source file:org.jboss.aerogear.unifiedpush.jpa.dao.impl.JPAInstallationDao.java

License:Apache License

@Override
public ResultsStream.QueryBuilder<String> findAllDeviceTokenForVariantIDByCriteria(String variantID,
        List<String> categories, List<String> aliases, List<String> deviceTypes, final int maxResults,
        String lastTokenFromPreviousBatch) {
    // the required part: Join + all tokens for variantID;

    final StringBuilder jpqlString = new StringBuilder(FIND_ALL_DEVICES_FOR_VARIANT_QUERY);
    final Map<String, Object> parameters = new LinkedHashMap<String, Object>();
    parameters.put("variantID", variantID);

    // apend query conditions based on specified message parameters
    appendDynamicQuery(jpqlString, parameters, categories, aliases, deviceTypes);

    // sort on ids so that we can handle paging properly
    if (lastTokenFromPreviousBatch != null) {
        jpqlString.append(" AND installation.deviceToken > :lastTokenFromPreviousBatch");
        parameters.put("lastTokenFromPreviousBatch", lastTokenFromPreviousBatch);
    }/*w ww  .j ava  2  s  .c om*/

    jpqlString.append(" ORDER BY installation.deviceToken ASC");

    return new ResultsStream.QueryBuilder<String>() {
        private Integer fetchSize = null;

        @Override
        public ResultsStream.QueryBuilder<String> fetchSize(int fetchSize) {
            this.fetchSize = fetchSize;
            return this;
        }

        @Override
        public ResultsStream<String> executeQuery() {
            Query hibernateQuery = JPAInstallationDao.this.createHibernateQuery(jpqlString.toString());
            hibernateQuery.setMaxResults(maxResults);
            for (Entry<String, Object> parameter : parameters.entrySet()) {
                Object value = parameter.getValue();
                if (value instanceof Collection<?>) {
                    hibernateQuery.setParameterList(parameter.getKey(), (Collection<?>) parameter.getValue());
                } else {
                    hibernateQuery.setParameter(parameter.getKey(), parameter.getValue());
                }

            }
            hibernateQuery.setReadOnly(true);
            if (fetchSize != null) {
                hibernateQuery.setFetchSize(fetchSize);
            }
            final ScrollableResults results = hibernateQuery.scroll(ScrollMode.FORWARD_ONLY);
            return new ResultsStream<String>() {
                @Override
                public boolean next() throws ResultStreamException {
                    return results.next();
                }

                @Override
                public String get() throws ResultStreamException {
                    return (String) results.get()[0];
                }
            };
        }

    };
}

From source file:org.jpos.gl.GLSession.java

License:Open Source License

private void deleteGLTransactions(Journal journal, Date start, Date end)
        throws HibernateException, GLException {
    boolean equalDate = start.equals(end);

    StringBuffer qs = new StringBuffer("from org.jpos.gl.GLTransaction where journal = :journal");
    if (equalDate) {
        qs.append(" and postDate = :date");
    } else {/*www  .  j  a v a 2s.  co m*/
        qs.append(" and postDate >= :start");
        qs.append(" and postDate <= :endDate");
    }
    Query q = session.createQuery(qs.toString());
    q.setLong("journal", journal.getId());
    if (equalDate)
        q.setParameter("date", start);
    else {
        q.setParameter("start", start);
        q.setParameter("endDate", end);
    }
    ScrollableResults sr = q.scroll(ScrollMode.FORWARD_ONLY);
    while (sr.next()) {
        session.delete(sr.get(0));
    }
}

From source file:org.ng200.openolympus.services.TaskService.java

License:Open Source License

@PreAuthorize(SecurityExpressionConstants.IS_ADMIN)
@Transactional/*from   ww w. j a va 2s  .  c o  m*/
public void rejudgeTask(final Task task) throws ExecutionException, IOException {

    final Lock lock = task.writeLock();
    lock.lock();

    try {

        this.verdictRepository.flush();
        this.solutionRepository.flush();

        this.verdictRepository.deleteBySolutionTask(task);
        this.verdictRepository.flush();

        final StatelessSession session = ((Session) this.entityManager.getDelegate()).getSessionFactory()
                .openStatelessSession();
        try {
            final Query query = session.createQuery("from Solution where task_id=:taskID");
            query.setParameter("taskID", task.getId());
            query.setFetchSize(Integer.valueOf(1000));
            query.setReadOnly(false);
            final ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY);
            try {
                while (results.next()) {
                    final Solution solution = (Solution) results.get(0);
                    this.testingService.testSolutionOnAllTests(solution);
                }
            } finally {
                results.close();
            }
        } finally {
            session.close();
        }
    } finally {
        lock.unlock();
    }
}