List of usage examples for org.hibernate Query scroll
ScrollableResults scroll(ScrollMode scrollMode);
From source file:org.candlepin.model.ColumnarResultIteratorTest.java
License:Open Source License
@Test(expected = NoSuchElementException.class) public void testNextWithoutElements() { Query query = this.session.createQuery("SELECT o FROM Owner o"); ColumnarResultIterator<Owner> iterator = new ColumnarResultIterator<>(this.session, query.scroll(ScrollMode.FORWARD_ONLY), 0, false); try {//from w w w . j a v a2s .c om iterator.next(); // Kaboom } finally { iterator.close(); } }
From source file:org.candlepin.model.ColumnarResultIteratorTest.java
License:Open Source License
@Test(expected = UnsupportedOperationException.class) public void testRemoveAlwaysFails() { this.ownerCurator.create(TestUtil.createOwner()); Query query = this.session.createQuery("SELECT o FROM Owner o"); ColumnarResultIterator<Owner> iterator = new ColumnarResultIterator<>(this.session, query.scroll(ScrollMode.FORWARD_ONLY), 0, false); try {/*from ww w . ja v a 2 s . c o m*/ iterator.next(); iterator.remove(); } finally { iterator.close(); } }
From source file:org.candlepin.model.RowResultIteratorTest.java
License:Open Source License
@Test public void testHasNextWithElements() { this.ownerCurator.create(TestUtil.createOwner()); Query query = this.session.createQuery("SELECT o FROM Owner o"); RowResultIterator iterator = new RowResultIterator(query.scroll(ScrollMode.FORWARD_ONLY)); try {/*w w w .j av a 2 s . com*/ assertTrue(iterator.hasNext()); } finally { iterator.close(); } }
From source file:org.candlepin.model.RowResultIteratorTest.java
License:Open Source License
@Test public void testHasNextWithoutElements() { Query query = this.session.createQuery("SELECT o FROM Owner o"); RowResultIterator iterator = new RowResultIterator(query.scroll(ScrollMode.FORWARD_ONLY)); try {//w w w. j a v a 2 s . com assertFalse(iterator.hasNext()); } finally { iterator.close(); } }
From source file:org.candlepin.model.RowResultIteratorTest.java
License:Open Source License
@Test public void testNextWithElements() { Owner owner1 = TestUtil.createOwner(); Owner owner2 = TestUtil.createOwner(); Owner owner3 = TestUtil.createOwner(); this.ownerCurator.create(owner1); this.ownerCurator.create(owner2); this.ownerCurator.create(owner3); Query query = this.session.createQuery("SELECT o FROM Owner o"); RowResultIterator iterator = new RowResultIterator(query.scroll(ScrollMode.FORWARD_ONLY)); try {/*ww w . j a v a 2 s. c o m*/ List<Owner> owners = new LinkedList<>(); // Note: Since we're testing everything in isolation here, we can't // be expecting .hasNext to be functional here. :) owners.add((Owner) iterator.next()[0]); owners.add((Owner) iterator.next()[0]); owners.add((Owner) iterator.next()[0]); assertTrue(owners.contains(owner1)); assertTrue(owners.contains(owner2)); assertTrue(owners.contains(owner3)); } finally { iterator.close(); } }
From source file:org.candlepin.model.RowResultIteratorTest.java
License:Open Source License
@Test(expected = NoSuchElementException.class) public void testNextWithoutElements() { Query query = this.session.createQuery("SELECT o FROM Owner o"); RowResultIterator iterator = new RowResultIterator(query.scroll(ScrollMode.FORWARD_ONLY)); try {/*from w w w. j a v a2s. c o m*/ iterator.next(); // Kaboom } finally { iterator.close(); } }
From source file:org.candlepin.model.RowResultIteratorTest.java
License:Open Source License
@Test(expected = UnsupportedOperationException.class) public void testRemoveAlwaysFails() { this.ownerCurator.create(TestUtil.createOwner()); Query query = this.session.createQuery("SELECT o FROM Owner o"); RowResultIterator iterator = new RowResultIterator(query.scroll(ScrollMode.FORWARD_ONLY)); try {//w w w . j av a2s . co m iterator.next(); iterator.remove(); } finally { iterator.close(); } }
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 w w . ja v a2 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.Hibernate3ScrollableResultsGpsDevice.java
License:Apache License
/** * Indexes the data//from w w w .j a v a2s.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 ww.j a v a 2s . 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); } }