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: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;
        }/*from   w  ww .  j  a  v a 2 s  . c om*/
        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.Hibernate3Dialect.java

License:Apache License

public String getStringValue(ScrollableResults rs, String[] returnAliases, ColumnMapping mapping) {
    int index = -1;
    if (mapping.isUsingColumnIndex()) {
        index = mapping.getColumnIndex();
    } else {//w  ww.  j a v  a 2 s.co m
        index = getIndex(returnAliases, mapping);
    }
    Type type = rs.getType(index);
    String result;
    if (type instanceof StringType) {
        result = rs.getString(index);
    } else {
        result = rs.get(index).toString();
    }
    return result;
}

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

License:Apache License

public Object getValue(ScrollableResults rs, String[] returnAliases, ColumnMapping mapping) {
    int index = -1;
    if (mapping.isUsingColumnIndex()) {
        index = mapping.getColumnIndex();
    } else {//from   w  w  w  .j  a v a 2  s  .  c  om
        index = getIndex(returnAliases, mapping);
    }
    return rs.get(index);
}

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

License:Apache License

public String getStringValue(ScrollableResults rs, int columnIndex) {
    Type type = rs.getType(columnIndex);
    String result;//from w  w  w . jav  a2  s.com
    if (type instanceof StringType) {
        result = rs.getString(columnIndex);
    } else {
        result = rs.get(columnIndex).toString();
    }
    return result;
}

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

License:Apache License

/**
 * Index the given <code>ResultSet</code> row into a Compass
 * <code>Resource</code>.//  www.j  ava  2s  .com
 */
protected Object processRowValue(Object description, ScrollableResults rs, String[] returnAliases,
        CompassSession session) throws CompassException {

    if (log.isDebugEnabled()) {
        StringBuffer sb = new StringBuffer();
        sb.append(buildMessage("Indexing data 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());
    }

    ResultSetToResourceMapping mapping = (ResultSetToResourceMapping) description;

    HibernateAliasRowSnapshot rowSnapshot = null;
    if (shouldMirrorDataChanges() && mapping.supportsVersioning()) {
        rowSnapshot = new HibernateAliasRowSnapshot();
    }
    Resource resource = session.createResource(mapping.getAlias());
    Hibernate3ScrollableResultsRowMarshallHelper marshallHelper = new Hibernate3ScrollableResultsRowMarshallHelper(
            mapping, session, resource, rowSnapshot);
    marshallHelper.marshallResultSet(rs, returnAliases);

    if (shouldMirrorDataChanges() && mapping.supportsVersioning()) {
        snapshot.getAliasSnapshot(mapping.getAlias()).putRow(rowSnapshot);
    }

    return resource;
}

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

License:Apache License

/**
 * Performs the data change mirroring operation.
 */// ww  w .j  a va2s .co 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.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;
        }// w  w  w  .ja  va2 s . 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

@Override
protected Attributes toAttributes(ScrollableResults results) {
    long seriesPk = results.getLong(0);
    String retrieveAETs = results.getString(1);
    String externalRetrieveAET = results.getString(2);
    Availability availability = (Availability) results.get(3);
    byte[] instAttributes = results.getBinary(4);
    if (this.seriesPk != seriesPk) {
        this.seriesAttrs = querySeriesAttrs(seriesPk);
        this.seriesPk = seriesPk;
    }/* w w w  . jav a  2  s .  co  m*/
    Attributes attrs = new Attributes(seriesAttrs);
    Utils.decodeAttributes(attrs, instAttributes);
    Utils.setRetrieveAET(attrs, retrieveAETs, externalRetrieveAET);
    Utils.setAvailability(attrs, availability);
    return attrs;
}

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

License:LGPL

@Override
protected Attributes toAttributes(ScrollableResults results) {
    int numberOfStudyRelatedSeries = results.getInteger(0);
    int numberOfStudyRelatedInstances = results.getInteger(1);
    int numberOfSeriesRelatedInstances = results.getInteger(2);
    String modalitiesInStudy = results.getString(3);
    String sopClassesInStudy = results.getString(4);
    String retrieveAETs = results.getString(5);
    String externalRetrieveAET = results.getString(6);
    Availability availability = (Availability) results.get(7);
    byte[] seriesAttributes = results.getBinary(8);
    byte[] studyAttributes = results.getBinary(9);
    byte[] patientAttributes = results.getBinary(10);
    Attributes attrs = new Attributes();
    Utils.decodeAttributes(attrs, patientAttributes);
    Utils.decodeAttributes(attrs, studyAttributes);
    Utils.decodeAttributes(attrs, seriesAttributes);
    Utils.setStudyQueryAttributes(attrs, numberOfStudyRelatedSeries, numberOfStudyRelatedInstances,
            modalitiesInStudy, sopClassesInStudy);
    Utils.setSeriesQueryAttributes(attrs, numberOfSeriesRelatedInstances);
    Utils.setRetrieveAET(attrs, retrieveAETs, externalRetrieveAET);
    Utils.setAvailability(attrs, availability);
    return attrs;
}

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

License:LGPL

@Override
protected Attributes toAttributes(ScrollableResults results) {
    int numberOfStudyRelatedSeries = results.getInteger(0);
    int numberOfStudyRelatedInstances = results.getInteger(1);
    String modalitiesInStudy = results.getString(2);
    String sopClassesInStudy = results.getString(3);
    String retrieveAETs = results.getString(4);
    String externalRetrieveAET = results.getString(5);
    Availability availability = (Availability) results.get(6);
    byte[] studyAttributes = results.getBinary(7);
    byte[] patientAttributes = results.getBinary(8);
    Attributes attrs = new Attributes();
    Utils.decodeAttributes(attrs, patientAttributes);
    Utils.decodeAttributes(attrs, studyAttributes);
    Utils.setStudyQueryAttributes(attrs, numberOfStudyRelatedSeries, numberOfStudyRelatedInstances,
            modalitiesInStudy, sopClassesInStudy);
    Utils.setRetrieveAET(attrs, retrieveAETs, externalRetrieveAET);
    Utils.setAvailability(attrs, availability);
    return attrs;
}