Example usage for org.hibernate ScrollableResults close

List of usage examples for org.hibernate ScrollableResults close

Introduction

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

Prototype

void close();

Source Link

Document

Release resources immediately.

Usage

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

License:Open Source License

/**
 * {@inheritDoc}/*from   ww w .  j  a va  2 s .  com*/
 */
@Override
@Transactional
@SuppressWarnings("unchecked")
public int forEach(int column, boolean evict, ResultProcessor<T> processor) {
    if (processor == null) {
        throw new IllegalArgumentException("processor is null");
    }

    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);
    int count = 0;

    try {
        boolean cont = true;

        if (evict) {
            while (cont && cursor.next()) {
                T result = (T) cursor.get(column);

                cont = processor.process(result);
                this.session.evict(result);

                ++count;
            }
        } else {
            while (cont && cursor.next()) {
                cont = processor.process((T) cursor.get(column));
                ++count;
            }
        }
    } finally {
        cursor.close();
    }

    return count;
}

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

License:Open Source License

/**
 * {@inheritDoc}//from  w  w  w .  j  av a2s  .com
 */
@Override
@Transactional
public int forEachRow(ResultProcessor<Object[]> processor) {
    if (processor == null) {
        throw new IllegalArgumentException("processor is null");
    }

    Criteria executable = this.getExecutableCriteria();
    ScrollableResults cursor = executable.scroll(ScrollMode.FORWARD_ONLY);
    int count = 0;

    try {
        boolean cont = true;

        while (cont && cursor.next()) {
            cont = processor.process(cursor.get());
            ++count;
        }
    } finally {
        cursor.close();
    }

    return count;
}

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 va  2 s.co m*/
        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// w  ww.  j  a  v  a 2s . c  o  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);
}

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

License:Apache License

/**
 * Performs the data change mirroring operation.
 *///from w w w .j  a v  a 2 s.  c  o  m
public synchronized void performMirroring() throws HibernateGpsDeviceException {
    if (!shouldMirrorDataChanges() || isPerformingIndexOperation()) {
        return;
    }
    if (snapshot == null) {
        throw new IllegalStateException(buildMessage(
                "Versioning data was not properly initialized, did you index the device or loaded the data?"));
    }

    HibernateSessionWrapper sessionWrapper = doGetHibernateSessionWrapper();

    try {
        sessionWrapper.open();
        for (Iterator it = mappings.iterator(); it.hasNext();) {
            ResultSetToResourceMapping mapping = (ResultSetToResourceMapping) it.next();
            if (!mapping.supportsVersioning()) {
                continue;
            }
            HibernateAliasSnapshot oldAliasSnapshot = snapshot.getAliasSnapshot(mapping.getAlias());
            if (oldAliasSnapshot == null) {
                log.warn(buildMessage("No snapshot for alias [" + mapping.getAlias()
                        + "] even though there should be support for versioning ignoring the alias"));
                continue;
            }
            HibernateAliasSnapshot newAliasSnapshot = new HibernateAliasSnapshot(mapping.getAlias());
            ArrayList createdRows = new ArrayList();
            ArrayList updatedRows = new ArrayList();
            ArrayList deletedRows = new ArrayList();
            if (log.isDebugEnabled()) {
                log.debug(buildMessage("Executing version query [" + mapping.getVersionQuery() + "]"));
            }

            String[] returnAliases = null;

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

            String queryString = mapping.getVersionQuery();

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

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

            ScrollableResults rs = query.scroll(ScrollMode.FORWARD_ONLY);
            int count = 0;
            while (rs.next()) {
                if (log.isDebugEnabled()) {
                    StringBuffer sb = new StringBuffer();
                    sb.append(buildMessage("Version row with values "));
                    for (int i = 0; i != returnAliases.length; i++) {
                        sb.append("[").append(returnAliases[i]).append(":");
                        Object value = rs.get(i);
                        sb.append(value);
                        sb.append("] ");
                    }
                    log.debug(sb.toString());
                }

                HibernateAliasRowSnapshot newRowSnapshot = new HibernateAliasRowSnapshot();
                Hibernate3ScrollableResultsRowMarshallHelper marshallHelper = new Hibernate3ScrollableResultsRowMarshallHelper(
                        mapping, newRowSnapshot, compassGps.getMirrorCompass());
                marshallHelper.marshallResultSet(rs, returnAliases);

                // new and old have the same ids
                HibernateAliasRowSnapshot oldRowSnapshot = oldAliasSnapshot.getRow(newRowSnapshot);

                // new row or updated row
                if (oldRowSnapshot == null) {
                    createdRows.add(newRowSnapshot);
                } else if (oldRowSnapshot.isOlderThan(newRowSnapshot)) {
                    updatedRows.add(newRowSnapshot);
                }

                newAliasSnapshot.putRow(newRowSnapshot);

                if (++count % fetchCount == 0) {
                    // release memory
                    hibernateSession.flush();
                    hibernateSession.clear();
                }
            }
            rs.close();

            for (Iterator oldRowIt = oldAliasSnapshot.rowSnapshotIt(); oldRowIt.hasNext();) {
                HibernateAliasRowSnapshot tmpRow = (HibernateAliasRowSnapshot) oldRowIt.next();
                // deleted row
                if (newAliasSnapshot.getRow(tmpRow) == null) {
                    deletedRows.add(tmpRow);
                }
            }
            if (!createdRows.isEmpty() || !updatedRows.isEmpty()) {
                getSnapshotEventListener().onCreateAndUpdate(new CreateAndUpdateSnapshotEvent(hibernateSession,
                        mapping, createdRows, updatedRows, compassGps));
            }
            if (!deletedRows.isEmpty()) {
                getSnapshotEventListener()
                        .onDelete(new DeleteSnapshotEvent(hibernateSession, mapping, deletedRows, compassGps));
            }
            snapshot.putAliasSnapshot(newAliasSnapshot);
        }
    } catch (Exception e) {
        throw new HibernateGpsDeviceException(buildMessage("Failed while mirroring data changes"), e);
    } finally {
        sessionWrapper.close();
    }
    if (isSaveSnapshotAfterMirror()) {
        getSnapshotPersister().save(snapshot);
    }
}

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 w ww  .j a  v a 2 s  .co 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.compass.gps.device.jpa.indexer.HibernateJpaIndexEntitiesIndexer.java

License:Apache License

public void performIndex(CompassSession session, IndexEntity[] entities) {
    for (IndexEntity indexEntity : entities) {
        EntityInformation entityInformation = (EntityInformation) indexEntity;
        if (jpaGpsDevice.isFilteredForIndex(entityInformation.getName())) {
            continue;
        }/* ww w .  j av a2  s  .c  om*/
        int fetchCount = jpaGpsDevice.getFetchCount();
        if (!jpaGpsDevice.isRunning()) {
            return;
        }
        EntityManagerWrapper wrapper = jpaGpsDevice.getEntityManagerWrapper().newInstance();
        ScrollableResults cursor = null;
        try {
            wrapper.open();
            HibernateEntityManager entityManager = (HibernateEntityManager) wrapper.getEntityManager();
            entityManager.getSession().setCacheMode(CacheMode.IGNORE);
            if (log.isDebugEnabled()) {
                log.debug(jpaGpsDevice.buildMessage("Indexing entities [" + entityInformation.getName()
                        + "] using query [" + entityInformation.getQueryProvider() + "]"));
            }

            if (entityInformation.getQueryProvider() instanceof HibernateJpaQueryProvider) {
                Criteria criteria = ((HibernateJpaQueryProvider) entityInformation.getQueryProvider())
                        .createCriteria(entityManager, entityInformation);
                if (criteria != null) {
                    if (performOrderById) {
                        Boolean performOrder = performOrderByPerEntity.get(entityInformation.getName());
                        if (performOrder == null || performOrder) {
                            ClassMetadata metadata = entityManager.getSession().getSessionFactory()
                                    .getClassMetadata(entityInformation.getName());
                            String idPropName = metadata.getIdentifierPropertyName();
                            if (idPropName != null) {
                                criteria.addOrder(Order.asc(idPropName));
                            }
                        }
                    }
                    criteria.setFetchSize(fetchCount);
                    cursor = criteria.scroll(ScrollMode.FORWARD_ONLY);
                }
            }
            if (cursor == null) {
                HibernateQuery query = (HibernateQuery) entityInformation.getQueryProvider()
                        .createQuery(entityManager, entityInformation);
                cursor = query.getHibernateQuery().scroll(ScrollMode.FORWARD_ONLY);
            }

            // store things in row buffer to allow using batch fetching in Hibernate
            RowBuffer buffer = new RowBuffer(session, entityManager.getSession(), fetchCount);
            Object prev = null;
            while (true) {
                try {
                    if (!cursor.next()) {
                        break;
                    }
                } catch (ObjectNotFoundException e) {
                    continue;
                }
                Object item = cursor.get(0);
                if (item != prev && prev != null) {
                    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();

            entityManager.clear();
            wrapper.close();
        } catch (Exception e) {
            log.error(jpaGpsDevice.buildMessage("Failed to index the database"), e);
            if (cursor != null) {
                try {
                    cursor.close();
                } catch (Exception e1) {
                    log.warn(jpaGpsDevice.buildMessage("Failed to close cursor on error, ignoring"), e1);
                }
            }
            wrapper.closeOnError();
            if (!(e instanceof JpaGpsDeviceException)) {
                throw new JpaGpsDeviceException(jpaGpsDevice.buildMessage("Failed to index the database"), e);
            }
            throw (JpaGpsDeviceException) e;
        }
    }
}

From source file:org.dcm4chee.archive.ejb.query.PatientNameQueryBean.java

License:LGPL

@Override
public String[] query(IDWithIssuer[] pids) {
    HashSet<String> c = new HashSet<String>(pids.length * 4 / 3 + 1);
    BooleanBuilder builder = new BooleanBuilder();
    builder.and(Builder.pids(pids, false));
    builder.and(QPatient.patient.mergedWith.isNull());
    ScrollableResults results = new HibernateQuery(session).from(QPatient.patient).where(builder)
            .scroll(ScrollMode.FORWARD_ONLY, QPatient.patient.pk, QPatient.patient.encodedAttributes);
    try {/*w w w  .  ja  v  a 2s . co m*/
        while (results.next())
            c.add(Utils.decodeAttributes(results.getBinary(1)).getString(Tag.PatientName));
    } finally {
        results.close();
    }
    c.remove(null);
    return c.isEmpty() ? null : c.toArray(new String[c.size()]);
}

From source file:org.drools.reteoo.JoinNode.java

License:Apache License

/**
 * Performs query to db. Operates on {@link RightRelationship} with
 * {@link ScrollableResults}. It's allows to operates on single fetched row,
 * not full query results. There is no need for flushing and/or clearing
 * cause that's read-only operation.//from   w ww.j  a v  a 2s  .c om
 * 
 * @param contextEntry
 * @param useLeftMemory
 * @param context
 * @param workingMemory
 * @param leftTuple
 */
private void getAndPropagateDBTupleFromLeft(ContextEntry[] contextEntry, boolean useLeftMemory,
        PropagationContext context, InternalWorkingMemory workingMemory, LeftTuple leftTuple) {
    int counterToClear = 0;
    m_relManager = DbRelationshipManager.getInstance();
    final Session session = m_relManager.openSession();
    final Query query = m_relManager.createQueryGetRightRelsByJoinNodeId(this.getId());
    final ScrollableResults iterator = m_relManager.getScrollableResultsIterator(query);
    while (iterator.next()) {
        final RightRelationship relationship = (RightRelationship) iterator.get()[0];
        final RightTuple rightTupleFromDb = createRightTuple(relationship, this);
        if ((++counterToClear % DbRelationshipManager.BATCH_SIZE) == 0) {
            session.clear();
        }
        propagateFromLeft(rightTupleFromDb, leftTuple, contextEntry, useLeftMemory, context, workingMemory);
    }
    iterator.close();
    session.close();
}

From source file:org.drools.reteoo.JoinNode.java

License:Apache License

/**
 * Performs query to db. Operates on {@link Relationship} with
 * {@link ScrollableResults}. It's allows to operates on single fetched row,
 * not full query results. There is no need for flushing and/or clearing
 * cause that's read-only operation./* ww w .  j  a v  a 2s  .c om*/
 * 
 * @param context
 *            - for propagating tuple.
 * @param workingMemory
 *            - for propagating tuple.
 * @param memory
 *            - for propagating tuple.
 * @param rightTuple
 *            - the tuple to propagate.
 */
private void getAndPropagateDBTupleFromRight(final PropagationContext context,
        final InternalWorkingMemory workingMemory, final BetaMemory memory, final RightTuple rightTuple) {
    int counterToClear = 0;
    m_relManager = DbRelationshipManager.getInstance();
    final Session session = m_relManager.openSession();
    final Query query = m_relManager.createQueryGetRelsByJoinNodeId(this.getId());
    final ScrollableResults iterator = m_relManager.getScrollableResultsIterator(query);
    while (iterator.next()) {
        final Relationship relationship = (Relationship) iterator.get()[0];
        final LeftTuple tupleFromDb = createLeftTuple(relationship, this);
        if ((++counterToClear % DbRelationshipManager.BATCH_SIZE) == 0) {
            session.clear();
        }
        propagateFromRight(rightTuple, tupleFromDb, memory, context, workingMemory);
    }
    iterator.close();
    session.close();
}