org.hibernate.ScrollableResults.get()

Here are the examples of the java api org.hibernate.ScrollableResults.get() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

15 Examples 7

19 Source : HibernatePersistenceService.java
with Apache License 2.0
from spot-next

private QueryResult executeQuery(JpqlQuery sourceQuery, Query query) {
    List values = new ArrayList<>();
    Integer totalCount = null;
    if (sourceQuery.getPageSize() > 0) {
        int start = (sourceQuery.getPage() > 0 ? sourceQuery.getPage() - 1 : 0) * sourceQuery.getPageSize();
        ScrollableResults scrollResult = null;
        try {
            scrollResult = query.scroll();
            if (start > 0) {
                scrollResult.scroll(start);
            }
            do {
                Object value = scrollResult.get();
                // this should actually not happen, but it does ...
                // TODO: check and fix null result objects
                if (value != null) {
                    if (value.getClreplaced().isArray()) {
                        Object[] valueArray = (Object[]) value;
                        if (valueArray.length > 0) {
                            values.add(valueArray[0]);
                        }
                    } else {
                        values.add(value);
                    }
                }
            } while (values.size() < sourceQuery.getPageSize() && scrollResult.next());
            // go to last row to get max rows
            scrollResult.last();
            totalCount = scrollResult.getRowNumber();
            // different implementations handle this either with a start index of 0 or 1 ...
            if (!(scrollResult instanceof FetchingScrollableResultsImpl)) {
                totalCount += 1;
            }
        } finally {
            MiscUtil.closeQuietly(scrollResult);
        }
    } else {
        values = query.list();
        totalCount = values.size();
    }
    QueryResult result = new QueryResult(values, sourceQuery.getPage(), sourceQuery.getPageSize(), totalCount != null ? Long.valueOf(totalCount) : null);
    return result;
}

18 Source : JRHibernateScrollDataSource.java
with GNU Lesser General Public License v3.0
from TIBCOSoftware

@Override
public boolean next() throws JRException {
    if (scrollableResults != null && scrollableResults.next()) {
        setCurrentRowValue(scrollableResults.get());
        return true;
    }
    return false;
}

18 Source : HibernateContextDAO.java
with Apache License 2.0
from isstac

@Override
@Transactional
public void updateSearchIndexForType(Clreplaced<?> type) {
    // From http://docs.jboss.org/hibernate/search/3.3/reference/en-US/html/manual-index-changes.html#search-batchindex-flushtoindexes
    FullTextSession session = Search.getFullTextSession(sessionFactory.getCurrentSession());
    session.purgeAll(type);
    // Prepare session for batch work
    session.flush();
    session.clear();
    FlushMode flushMode = session.getFlushMode();
    CacheMode cacheMode = session.getCacheMode();
    try {
        session.setFlushMode(FlushMode.MANUAL);
        session.setCacheMode(CacheMode.IGNORE);
        // Scrollable results will avoid loading too many objects in memory
        ScrollableResults results = session.createCriteria(type).setFetchSize(1000).scroll(ScrollMode.FORWARD_ONLY);
        int index = 0;
        while (results.next()) {
            index++;
            // index each element
            session.index(results.get(0));
            if (index % 1000 == 0) {
                // apply changes to indexes
                session.flushToIndexes();
                // free memory since the queue is processed
                session.clear();
            }
        }
        session.flushToIndexes();
        session.clear();
    } finally {
        session.setFlushMode(flushMode);
        session.setCacheMode(cacheMode);
    }
}

18 Source : DefaultStreamer.java
with Apache License 2.0
from IBM

private void streamRows(ScrollableResults results, FluxSink<T> sink) {
    while (results.next()) {
        sink.next(type.cast(results.get(0)));
    }
    sink.complete();
}

18 Source : HibernateSearch5InstrumentationTest.java
with Apache License 2.0
from elastic

@Test
void performScrollLuceneIndexSearch() {
    try (ScrollableResults scroll = createNonJpaFullTextQuery(createQueryForDog1()).scroll()) {
        replacedertThat(scroll.next()).isTrue();
        replacedertAll(() -> {
            Object[] dogs = scroll.get();
            replacedertThat(dogs.length).isEqualTo(1);
            replacedertThat(((Dog) dogs[0]).getName()).isEqualTo("dog1");
            replacedertThat(scroll.isFirst()).isTrue();
            replacedertThat(scroll.isLast()).isTrue();
            replacedertApmSpanInformation(reporter, "name:dog1", "scroll");
        });
    }
}

17 Source : SqlAuditServiceImpl.java
with Apache License 2.0
from Pardus-Engerek

private void listRecordsIterativeAttempt(String query, Map<String, Object> params, AuditResultHandler handler) {
    Session session = null;
    int count = 0;
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("List records attempt\n  query: {}\n params:\n{}", query, DebugUtil.debugDump(params, 2));
    }
    try {
        session = baseHelper.beginReadOnlyTransaction();
        Query q;
        if (StringUtils.isBlank(query)) {
            query = "from RAuditEventRecord as aer where 1=1 order by aer.timestamp desc";
            q = session.createQuery(query);
            setParametersToQuery(q, params);
        } else {
            q = session.createQuery(query);
            setParametersToQuery(q, params);
        }
        // q.setResultTransformer(Transformers.aliasToBean(RAuditEventRecord.clreplaced));
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("List records attempt\n  processed query: {}", q);
        }
        ScrollableResults resultList = q.scroll();
        while (resultList.next()) {
            Object o = resultList.get(0);
            if (!(o instanceof RAuditEventRecord)) {
                throw new DtoTranslationException("Unexpected object in result set. Expected audit record, but got " + o.getClreplaced().getSimpleName());
            }
            RAuditEventRecord raudit = (RAuditEventRecord) o;
            AuditEventRecord audit = RAuditEventRecord.fromRepo(raudit, getPrismContext());
            // TODO what if original name (in audit log) differs from the current one (in repo) ?
            audit.setInitiator(resolve(session, raudit.getInitiatorOid(), raudit.getInitiatorName(), RObjectType.USER));
            audit.setTarget(resolve(session, raudit.getTargetOid(), raudit.getTargetName(), raudit.getTargetType()));
            audit.setTargetOwner(resolve(session, raudit.getTargetOwnerOid(), raudit.getTargetOwnerName(), RObjectType.USER));
            count++;
            if (!handler.handle(audit)) {
                LOGGER.trace("Skipping handling of objects after {} was handled. ", audit);
                break;
            }
        }
        session.getTransaction().commit();
    } catch (DtoTranslationException | SchemaException ex) {
        baseHelper.handleGeneralCheckedException(ex, session, null);
    } catch (RuntimeException ex) {
        baseHelper.handleGeneralRuntimeException(ex, session, null);
    } finally {
        baseHelper.cleanupSessionAndResult(session, null);
    }
    LOGGER.trace("List records iterative attempt processed {} records", count);
}

17 Source : DefaultStreamerTest.java
with Apache License 2.0
from IBM

private void setupTransactionMocks(IsolationLevel level) throws SQLException {
    when(factory.openStatelessSession()).thenReturn(session);
    when(session.createQuery(QUERY, Person.clreplaced)).thenReturn(query);
    when(query.setFetchSize(DefaultStreamer.DEFAULT_FETCH_SIZE)).thenReturn(query);
    when(query.setReadOnly(true)).thenReturn(query);
    when(query.scroll(ScrollMode.FORWARD_ONLY)).thenReturn(results);
    when(results.next()).thenReturn(true).thenReturn(false);
    when(results.get(0)).thenReturn(PERSON);
    if (level != null) {
        when(session.getTransaction()).thenReturn(transaction);
        when(session.connection()).thenReturn(connection);
        if (level != IsolationLevel.DEFAULT) {
            when(connection.getTransactionIsolation()).thenReturn(Connection.TRANSACTION_NONE);
        }
    }
}

16 Source : DatabaseTest.java
with Apache License 2.0
from IBM

private void setupStreamTransactionMocks(IsolationLevel level) throws SQLException {
    when(sessionFactory.openStatelessSession()).thenReturn(statelessSession);
    when(statelessSession.createQuery(DefaultStreamerTest.QUERY, Person.clreplaced)).thenReturn(query);
    when(query.setFetchSize(DefaultStreamer.DEFAULT_FETCH_SIZE)).thenReturn(query);
    when(query.setReadOnly(true)).thenReturn(query);
    when(query.scroll(ScrollMode.FORWARD_ONLY)).thenReturn(results);
    when(results.next()).thenReturn(true).thenReturn(false);
    when(results.get(0)).thenReturn(DefaultStreamerTest.PERSON);
    if (level != null) {
        when(statelessSession.getTransaction()).thenReturn(transaction);
        when(statelessSession.connection()).thenReturn(connection);
        if (level != IsolationLevel.DEFAULT) {
            when(connection.getTransactionIsolation()).thenReturn(Connection.TRANSACTION_NONE);
        }
    }
}

15 Source : QueryConverter.java
with Apache License 2.0
from HongZhaoHua

@Override
public int convert(DataModule module, ScrollableResults iterator) {
    int count = 0;
    Int2IntSortedMap qualityFeatures = new Int2IntRBTreeMap();
    Int2FloatSortedMap quanreplacedyFeatures = new Int2FloatRBTreeMap();
    int size = module.getQualityOrder() + module.getQuanreplacedyOrder();
    try {
        while (iterator.next()) {
            for (int index = 0; index < size; index++) {
                Object data = iterator.get(index);
                if (data == null) {
                    continue;
                }
                Entry<Integer, KeyValue<String, Boolean>> term = module.getOuterKeyValue(index);
                KeyValue<String, Boolean> keyValue = term.getValue();
                if (keyValue.getValue()) {
                    QualityAttribute attribute = qualityAttributes.get(keyValue.getKey());
                    data = ConversionUtility.convert(data, attribute.getType());
                    int feature = attribute.convertData((Comparable) data);
                    qualityFeatures.put(module.getQualityInner(keyValue.getKey()) + index - term.getKey(), feature);
                } else {
                    QuanreplacedyAttribute attribute = quanreplacedyAttributes.get(keyValue.getKey());
                    data = ConversionUtility.convert(data, attribute.getType());
                    float feature = attribute.convertData((Number) data);
                    quanreplacedyFeatures.put(module.getQuanreplacedyInner(keyValue.getKey()) + index - term.getKey(), feature);
                }
            }
            module.replacedociateInstance(qualityFeatures, quanreplacedyFeatures);
            qualityFeatures.clear();
            quanreplacedyFeatures.clear();
            count++;
        }
    } catch (HibernateException exception) {
        // TODO 处理日志.
        throw new RuntimeException(exception);
    }
    return count;
}

14 Source : IndexHelper.java
with GNU General Public License v2.0
from openkm

protected int doRebuildIndex() throws Exception {
    FullTextSession fullTextSession = (FullTextSession) enreplacedyManager.getDelegate();
    fullTextSession.setFlushMode(org.hibernate.FlushMode.MANUAL);
    fullTextSession.setCacheMode(org.hibernate.CacheMode.IGNORE);
    fullTextSession.purgeAll(NodeDoreplacedentVersion.clreplaced);
    fullTextSession.getSearchFactory().optimize(NodeDoreplacedentVersion.clreplaced);
    String query = "select ndv from NodeDoreplacedentVersion ndv";
    ScrollableResults cursor = fullTextSession.createQuery(query).scroll();
    cursor.last();
    int count = cursor.getRowNumber() + 1;
    log.warn("Re-building Wine index for " + count + " objects.");
    if (count > 0) {
        int batchSize = 300;
        // Reset to first result row
        cursor.first();
        int i = 0;
        while (true) {
            fullTextSession.index(cursor.get(0));
            if (++i % batchSize == 0) {
                fullTextSession.flushToIndexes();
                // Clear persistence context for each batch
                fullTextSession.clear();
                log.info("Flushed index update " + i + " from Thread " + Thread.currentThread().getName());
            }
            if (cursor.isLast()) {
                break;
            }
            cursor.next();
        }
    }
    cursor.close();
    fullTextSession.flushToIndexes();
    // Clear persistence context for each batch
    fullTextSession.clear();
    fullTextSession.getSearchFactory().optimize(NodeDoreplacedentVersion.clreplaced);
    return count;
}

12 Source : AddLastActionDate.java
with Apache License 2.0
from openequella

@Override
protected void executeDataMigration(HibernateMigrationHelper helper, MigrationResult result, Session session) {
    Query query = session.createQuery("select i.id, i.moderation.id from Item i where moderating = true or status = 'rejected'");
    ScrollableResults results = query.scroll();
    while (results.next()) {
        Query upQuery = session.createQuery("update ModerationStatus m set lastAction = " + "(select max(h.date) from Item i join i.history h where i.id = ?0 and h.type in ('approved','rejected', 'comment') group by i.id) " + "where m.id = ?1");
        upQuery.setParameter(0, results.get(0));
        upQuery.setParameter(1, results.get(1));
        upQuery.executeUpdate();
    }
}

10 Source : MigrateNotifications.java
with Apache License 2.0
from openequella

@Override
protected void executeDataMigration(HibernateMigrationHelper helper, MigrationResult result, Session session) {
    Date convertDate = new Date();
    Query query = session.createSQLQuery("SELECT i.uuid, i.version, i.insreplacedution_id," + " un.element FROM item_users_notified un INNER JOIN item i ON i.id = un.item_id");
    ScrollableResults results = query.scroll();
    while (results.next()) {
        Object[] oldnote = results.get();
        ItemId itemId = new ItemId((String) oldnote[0], ((Number) oldnote[1]).intValue());
        Insreplacedution inst = new Insreplacedution();
        inst.setDatabaseId(((Number) oldnote[2]).longValue());
        FakeNotification notification = new FakeNotification();
        notification.reason = FakeNotification.REASON_WENTLIVE;
        notification.date = convertDate;
        notification.itemid = itemId.toString();
        notification.insreplacedution = inst;
        notification.userTo = (String) oldnote[3];
        session.save(notification);
        session.flush();
        session.clear();
    }
}

9 Source : UpdateDefaultMimeTypeIcons.java
with Apache License 2.0
from openequella

@Override
protected void executeDataMigration(HibernateMigrationHelper helper, MigrationResult result, Session session) throws Exception {
    ScrollableResults results = session.createQuery("FROM MimeEntryAttributes WHERE element LIKE '%.gif' AND mapkey = 'PluginIconPath' ").scroll();
    while (results.next()) {
        Object[] resultEntry = results.get();
        FakeMimeEntryAttributes fmeAttr = (FakeMimeEntryAttributes) resultEntry[0];
        fmeAttr.element = fmeAttr.element.replaceAll(".gif", ".png");
        session.save(fmeAttr);
        session.flush();
        session.clear();
    }
}

8 Source : XmlExportCreator.java
with European Union Public License 1.1
from EUSurvey

@Transactional
public void simulateExportContent(boolean sync, Export export) throws Exception {
    exportedUniqueCodes.clear();
    Session session;
    session = sessionFactory.getCurrentSession();
    if (export != null) {
        session.evict(export.getSurvey());
    }
    exportedNow = new Date();
    List<List<String>> answersets = reportingService.getAnswerSets(form.getSurvey(), export == null ? null : export.getResultFilter(), null, false, true, true, true, true);
    if (answersets != null) {
        for (List<String> row : answersets) {
            int answerSetId = ConversionTools.getValue(row.get(1));
            String answerSetUniqueCode = row.get(0);
            if (!exportedUniqueCodes.containsKey(answerSetId)) {
                exportedUniqueCodes.put(answerSetId, answerSetUniqueCode);
            }
        }
    } else {
        HashMap<String, Object> values = new HashMap<>();
        String sql = "select ans.ANSWER_SET_ID, a.QUESTION_ID, a.QUESTION_UID, a.VALUE, a.ANSWER_COL, a.ANSWER_ID, a.ANSWER_ROW, a.PA_ID, a.PA_UID, ans.UNIQUECODE, ans.ANSWER_SET_DATE, ans.ANSWER_SET_UPDATE, ans.ANSWER_SET_INVID, ans.RESPONDER_EMAIL, ans.ANSWER_SET_LANG FROM ANSWERS a RIGHT JOIN ANSWERS_SET ans ON a.AS_ID = ans.ANSWER_SET_ID where ans.ANSWER_SET_ID IN (" + answerService.getSql(null, form.getSurvey().getId(), export == null ? null : export.getResultFilter(), values, true) + ") ORDER BY ans.ANSWER_SET_ID";
        SQLQuery query = session.createSQLQuery(sql);
        query.setReadOnly(true);
        for (Entry<String, Object> entry : values.entrySet()) {
            Object value = entry.getValue();
            if (value instanceof String) {
                query.setString(entry.getKey(), (String) value);
            } else if (value instanceof Integer) {
                query.setInteger(entry.getKey(), (Integer) value);
            } else if (value instanceof Date) {
                query.setTimestamp(entry.getKey(), (Date) value);
            }
        }
        query.setFetchSize(Integer.MIN_VALUE);
        ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY);
        while (results.next()) {
            Object[] a = results.get();
            if (!exportedUniqueCodes.containsKey(ConversionTools.getValue(a[0]))) {
                exportedUniqueCodes.put(ConversionTools.getValue(a[0]), (String) a[9]);
            }
        }
        results.close();
    }
}

7 Source : CreateTaskHistoryTable.java
with Apache License 2.0
from openequella

@Override
protected void executeDataMigration(HibernateMigrationHelper helper, MigrationResult result, Session session) {
    Query query = session.createQuery("update Item set moderating = true, dateForIndex = ?0 where status = 'MODERATING' and moderating = false");
    query.setParameter(0, new Date());
    int fixes = query.executeUpdate();
    if (fixes > 0) {
        result.addLogEntry(new MigrationStatusLog(LogType.WARNING, keyPrefix + "wrongmod", fixes));
    }
    ScrollableResults results = session.createQuery("SELECT ws.started, i.id, ws.wnode.id FROM Item i JOIN i.moderation AS ms JOIN ms.statuses AS ws " + "WHERE ws.status = 'i' AND ws.acttype = 'task' and i.moderating = true").scroll();
    while (results.next()) {
        Object[] resultArray = results.get();
        Date started = (Date) resultArray[0];
        FakeItem i = new FakeItem();
        i.id = ((Number) resultArray[1]).longValue();
        FakeWorkflowItem wi = new FakeWorkflowItem();
        wi.id = ((Number) resultArray[2]).longValue();
        FakeTaskHistory th = new FakeTaskHistory();
        th.item = i;
        th.task = wi;
        th.entryDate = started;
        th.exitDate = null;
        session.save(th);
        session.flush();
        session.clear();
    }
}