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.compass.gps.device.hibernate.scrollable.Hibernate3ScrollableResultsGpsDevice.java

License:Apache License

/**
 * Performs the data change mirroring operation.
 *//*  w  w  w  .jav  a2 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  ww  w.  j  a  va  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;
        }/*from  w w  w .  j  av  a  2s.co m*/
        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.InstanceQueryImpl.java

License:LGPL

private static ScrollableResults query(StatelessSession session, IDWithIssuer[] pids, Attributes keys,
        QueryParam queryParam) {/* w  w  w.  ja  va 2 s.  c  o  m*/
    BooleanBuilder builder = new BooleanBuilder();
    Builder.addPatientLevelPredicates(builder, pids, keys, queryParam);
    Builder.addStudyLevelPredicates(builder, keys, queryParam);
    Builder.addSeriesLevelPredicates(builder, keys, queryParam);
    Builder.addInstanceLevelPredicates(builder, keys, queryParam);
    return new HibernateQuery(session).from(QInstance.instance)
            .innerJoin(QInstance.instance.series, QSeries.series).innerJoin(QSeries.series.study, QStudy.study)
            .innerJoin(QStudy.study.patient, QPatient.patient).where(builder).scroll(ScrollMode.FORWARD_ONLY,
                    QSeries.series.pk, QInstance.instance.retrieveAETs, QInstance.instance.externalRetrieveAET,
                    QInstance.instance.availability, QInstance.instance.encodedAttributes);
}

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

License:LGPL

@Override
public void findScheduledProcedureSteps(IDWithIssuer[] pids, Attributes keys, QueryParam queryParam) {
    BooleanBuilder builder = new BooleanBuilder();
    Builder.addPatientLevelPredicates(builder, pids, keys, queryParam);
    Builder.addServiceRequestPredicates(builder, keys, queryParam);
    Builder.addRequestedProcedurePredicates(builder, keys, queryParam);
    Attributes spsItem = keys.getNestedDataset(Tag.ScheduledProcedureStepSequence);
    Builder.addScheduledProcedureStepPredicates(builder, spsItem, queryParam);
    results = new HibernateQuery(session).from(QScheduledProcedureStep.scheduledProcedureStep)
            .innerJoin(QScheduledProcedureStep.scheduledProcedureStep.requestedProcedure,
                    QRequestedProcedure.requestedProcedure)
            .innerJoin(QRequestedProcedure.requestedProcedure.serviceRequest, QServiceRequest.serviceRequest)
            .innerJoin(QServiceRequest.serviceRequest.visit, QVisit.visit)
            .innerJoin(QVisit.visit.patient, QPatient.patient).where(builder).scroll(ScrollMode.FORWARD_ONLY,
                    QScheduledProcedureStep.scheduledProcedureStep.encodedAttributes,
                    QRequestedProcedure.requestedProcedure.encodedAttributes,
                    QServiceRequest.serviceRequest.encodedAttributes, QVisit.visit.encodedAttributes,
                    QPatient.patient.encodedAttributes);
    hasNext = results.next();/*from  w  w w  . ja  v a2  s  .c o m*/
}

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 {/*from   w w  w  . j a  va 2 s. c o  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.dcm4chee.archive.ejb.query.PatientQueryImpl.java

License:LGPL

private static ScrollableResults query(StatelessSession session, IDWithIssuer[] pids, Attributes keys,
        QueryParam queryParam) {/*from w  ww .  ja v a2  s.  c o m*/
    BooleanBuilder builder = new BooleanBuilder();
    Builder.addPatientLevelPredicates(builder, pids, keys, queryParam);
    return new HibernateQuery(session).from(QPatient.patient).where(builder).scroll(ScrollMode.FORWARD_ONLY,
            QPatient.patient.pk, QPatient.patient.encodedAttributes);
}

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

License:LGPL

private static ScrollableResults query(StatelessSession session, IDWithIssuer[] pids, Attributes keys,
        QueryParam queryParam) {/*from  w ww  .  j  a v  a 2  s .c  om*/
    BooleanBuilder builder = new BooleanBuilder();
    Builder.addPatientLevelPredicates(builder, pids, keys, queryParam);
    Builder.addStudyLevelPredicates(builder, keys, queryParam);
    Builder.addSeriesLevelPredicates(builder, keys, queryParam);
    return new HibernateQuery(session).from(QSeries.series).innerJoin(QSeries.series.study, QStudy.study)
            .innerJoin(QStudy.study.patient, QPatient.patient).where(builder).scroll(ScrollMode.FORWARD_ONLY,
                    QStudy.study.numberOfStudyRelatedSeries, QStudy.study.numberOfStudyRelatedInstances,
                    QSeries.series.numberOfSeriesRelatedInstances, QStudy.study.modalitiesInStudy,
                    QStudy.study.sopClassesInStudy, QSeries.series.retrieveAETs,
                    QSeries.series.externalRetrieveAET, QSeries.series.availability,
                    QSeries.series.encodedAttributes, QStudy.study.encodedAttributes,
                    QPatient.patient.encodedAttributes);
}

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

License:LGPL

private static ScrollableResults query(StatelessSession session, IDWithIssuer[] pids, Attributes keys,
        QueryParam queryParam) {/*from w  w w  .  j  av a 2s. c  om*/
    BooleanBuilder builder = new BooleanBuilder();
    Builder.addPatientLevelPredicates(builder, pids, keys, queryParam);
    Builder.addStudyLevelPredicates(builder, keys, queryParam);
    return new HibernateQuery(session).from(QStudy.study).innerJoin(QStudy.study.patient, QPatient.patient)
            .where(builder).scroll(ScrollMode.FORWARD_ONLY, QStudy.study.numberOfStudyRelatedSeries,
                    QStudy.study.numberOfStudyRelatedInstances, QStudy.study.modalitiesInStudy,
                    QStudy.study.sopClassesInStudy, QStudy.study.retrieveAETs, QStudy.study.externalRetrieveAET,
                    QStudy.study.availability, QStudy.study.encodedAttributes,
                    QPatient.patient.encodedAttributes);
}

From source file:org.dcm4chee.archive.mwl.dao.MWLQueryService.java

License:LGPL

public void findScheduledProcedureSteps(IDWithIssuer[] pids, Attributes keys, QueryParam queryParam) {
    if (results != null)
        results.close();//from   ww  w  .  ja  va2  s.  com
    BooleanBuilder builder = new BooleanBuilder();
    Builder.addPatientLevelPredicates(builder, pids, keys, queryParam);
    Builder.addServiceRequestPredicates(builder, keys, queryParam);
    Builder.addRequestedProcedurePredicates(builder, keys, queryParam);
    Attributes spsItem = keys.getNestedDataset(Tag.ScheduledProcedureStepSequence);
    Builder.addScheduledProcedureStepPredicates(builder, spsItem, queryParam);
    results = new HibernateQuery(session).from(QScheduledProcedureStep.scheduledProcedureStep)
            .innerJoin(QScheduledProcedureStep.scheduledProcedureStep.requestedProcedure,
                    QRequestedProcedure.requestedProcedure)
            .innerJoin(QRequestedProcedure.requestedProcedure.serviceRequest, QServiceRequest.serviceRequest)
            .innerJoin(QServiceRequest.serviceRequest.visit, QVisit.visit)
            .innerJoin(QVisit.visit.patient, QPatient.patient).where(builder).scroll(ScrollMode.FORWARD_ONLY,
                    QScheduledProcedureStep.scheduledProcedureStep.encodedAttributes,
                    QRequestedProcedure.requestedProcedure.encodedAttributes,
                    QServiceRequest.serviceRequest.encodedAttributes, QVisit.visit.encodedAttributes,
                    QPatient.patient.encodedAttributes);
    hasNext = results.next();
}