use of org.hibernate.ScrollableResults in project hibernate-orm by hibernate.
the class StatelessSessionTest method testCreateUpdateReadDelete.
@Test
public void testCreateUpdateReadDelete() {
StatelessSession ss = sessionFactory().openStatelessSession();
Transaction tx = ss.beginTransaction();
Document doc = new Document("blah blah blah", "Blahs");
ss.insert(doc);
assertNotNull(doc.getName());
Date initVersion = doc.getLastModified();
assertNotNull(initVersion);
tx.commit();
tx = ss.beginTransaction();
doc.setText("blah blah blah .... blah");
ss.update(doc);
assertNotNull(doc.getLastModified());
assertNotSame(doc.getLastModified(), initVersion);
tx.commit();
tx = ss.beginTransaction();
doc.setText("blah blah blah .... blah blay");
ss.update(doc);
tx.commit();
Document doc2 = (Document) ss.get(Document.class.getName(), "Blahs");
assertEquals("Blahs", doc2.getName());
assertEquals(doc.getText(), doc2.getText());
doc2 = (Document) ss.createQuery("from Document where text is not null").uniqueResult();
assertEquals("Blahs", doc2.getName());
assertEquals(doc.getText(), doc2.getText());
ScrollableResults sr = ss.createQuery("from Document where text is not null").scroll(ScrollMode.FORWARD_ONLY);
sr.next();
doc2 = (Document) sr.get(0);
sr.close();
assertEquals("Blahs", doc2.getName());
assertEquals(doc.getText(), doc2.getText());
doc2 = (Document) ss.createSQLQuery("select * from Document").addEntity(Document.class).uniqueResult();
assertEquals("Blahs", doc2.getName());
assertEquals(doc.getText(), doc2.getText());
doc2 = (Document) ss.createCriteria(Document.class).uniqueResult();
assertEquals("Blahs", doc2.getName());
assertEquals(doc.getText(), doc2.getText());
sr = ss.createCriteria(Document.class).scroll(ScrollMode.FORWARD_ONLY);
sr.next();
doc2 = (Document) sr.get(0);
sr.close();
assertEquals("Blahs", doc2.getName());
assertEquals(doc.getText(), doc2.getText());
tx = ss.beginTransaction();
ss.delete(doc);
tx.commit();
ss.close();
}
use of org.hibernate.ScrollableResults in project hibernate-orm by hibernate.
the class StatsTest method testQueryStatGathering.
//
// @Test
// @SuppressWarnings( {"UnusedAssignment"})
// public void testCollectionFetchVsLoad() throws Exception {
// SessionFactory sf = buildBaseConfiguration()
// .setProperty( AvailableSettings.HBM2DDL_AUTO, "create-drop" )
// .buildSessionFactory();
//
// Session s = sf.openSession();
// Transaction tx = s.beginTransaction();
// Continent europe = fillDb(s);
// tx.commit();
// s.close();
//
// s = sf.openSession();
// tx = s.beginTransaction();
// assertEquals(0, sf.getStatistics().getCollectionLoadCount() );
// assertEquals(0, sf.getStatistics().getCollectionFetchCount() );
// Continent europe2 = (Continent) s.get( Continent.class, europe.getId() );
// assertEquals("Lazy true: no collection should be loaded", 0, sf.getStatistics().getCollectionLoadCount() );
// assertEquals( 0, sf.getStatistics().getCollectionFetchCount() );
// europe2.getCountries().size();
// assertEquals( 1, sf.getStatistics().getCollectionLoadCount() );
// assertEquals("Explicit fetch of the collection state", 1, sf.getStatistics().getCollectionFetchCount() );
// tx.commit();
// s.close();
//
// sf.getStatistics().clear();
//
// s = sf.openSession();
// tx = s.beginTransaction();
// europe = fillDb(s);
// tx.commit();
// s.clear();
// tx = s.beginTransaction();
// assertEquals( 0, sf.getStatistics().getCollectionLoadCount() );
// assertEquals( 0, sf.getStatistics().getCollectionFetchCount() );
// europe2 = (Continent) s.createQuery(
// "from " + Continent.class.getName() + " a join fetch a.countries where a.id = " + europe.getId()
// ).uniqueResult();
// assertEquals( 1, sf.getStatistics().getCollectionLoadCount() );
// assertEquals( "collection should be loaded in the same query as its parent", 0, sf.getStatistics().getCollectionFetchCount() );
// tx.commit();
// s.close();
//
// // open a new SF
// sf.close();
// Configuration cfg = buildBaseConfiguration().setProperty( AvailableSettings.HBM2DDL_AUTO, "create-drop" );
// cfg.buildMappings();
// Collection coll = cfg.getCollectionMapping(Continent.class.getName() + ".countries");
// coll.setFetchMode(FetchMode.JOIN);
// coll.setLazy(false);
// sf = cfg.buildSessionFactory();
//
// s = sf.openSession();
// tx = s.beginTransaction();
// europe = fillDb(s);
// tx.commit();
// s.close();
//
// s = sf.openSession();
// tx = s.beginTransaction();
// assertEquals( 0, sf.getStatistics().getCollectionLoadCount() );
// assertEquals( 0, sf.getStatistics().getCollectionFetchCount() );
// europe2 = (Continent) s.get( Continent.class, europe.getId() );
// assertEquals( 1, sf.getStatistics().getCollectionLoadCount() );
// assertEquals( "Should do direct load, not indirect second load when lazy false and JOIN", 0, sf.getStatistics().getCollectionFetchCount() );
// tx.commit();
// s.close();
// sf.close();
//
// // open yet another SF
// sf.close();
// cfg = buildBaseConfiguration().setProperty( AvailableSettings.HBM2DDL_AUTO, "create-drop" );
// cfg.buildMappings();
// coll = cfg.getCollectionMapping( Continent.class.getName() + ".countries" );
// coll.setFetchMode(FetchMode.SELECT);
// coll.setLazy(false);
// sf = cfg.buildSessionFactory();
//
// s = sf.openSession();
// tx = s.beginTransaction();
// europe = fillDb(s);
// tx.commit();
// s.close();
//
// s = sf.openSession();
// tx = s.beginTransaction();
// assertEquals( 0, sf.getStatistics().getCollectionLoadCount() );
// assertEquals( 0, sf.getStatistics().getCollectionFetchCount() );
// europe2 = (Continent) s.get( Continent.class, europe.getId() );
// assertEquals( 1, sf.getStatistics().getCollectionLoadCount() );
// assertEquals( "Should do explicit collection load, not part of the first one", 1, sf.getStatistics().getCollectionFetchCount() );
// for ( Object o : europe2.getCountries() ) {
// s.delete( o );
// }
// cleanDb( s );
// tx.commit();
// s.close();
//
// sf.close();
// }
@Test
public void testQueryStatGathering() {
SessionFactory sf = buildBaseConfiguration().setProperty(AvailableSettings.HBM2DDL_AUTO, "create-drop").buildSessionFactory();
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
fillDb(s);
tx.commit();
s.close();
s = sf.openSession();
tx = s.beginTransaction();
final String continents = "from Continent";
int results = s.createQuery(continents).list().size();
QueryStatistics continentStats = sf.getStatistics().getQueryStatistics(continents);
assertNotNull("stats were null", continentStats);
assertEquals("unexpected execution count", 1, continentStats.getExecutionCount());
assertEquals("unexpected row count", results, continentStats.getExecutionRowCount());
long maxTime = continentStats.getExecutionMaxTime();
assertEquals(maxTime, sf.getStatistics().getQueryExecutionMaxTime());
// assertEquals( continents, stats.getQueryExecutionMaxTimeQueryString() );
Iterator itr = s.createQuery(continents).iterate();
// iterate() should increment the execution count
assertEquals("unexpected execution count", 2, continentStats.getExecutionCount());
// but should not effect the cumulative row count
assertEquals("unexpected row count", results, continentStats.getExecutionRowCount());
Hibernate.close(itr);
ScrollableResults scrollableResults = s.createQuery(continents).scroll();
// same deal with scroll()...
assertEquals("unexpected execution count", 3, continentStats.getExecutionCount());
assertEquals("unexpected row count", results, continentStats.getExecutionRowCount());
// if data is not read beforeQuery closing the ResultSet
while (scrollableResults.next()) {
// do nothing
}
scrollableResults.close();
tx.commit();
s.close();
// explicitly check that statistics for "split queries" get collected
// under the original query
sf.getStatistics().clear();
s = sf.openSession();
tx = s.beginTransaction();
final String localities = "from Locality";
results = s.createQuery(localities).list().size();
QueryStatistics localityStats = sf.getStatistics().getQueryStatistics(localities);
assertNotNull("stats were null", localityStats);
// ...one for each split query
assertEquals("unexpected execution count", 2, localityStats.getExecutionCount());
assertEquals("unexpected row count", results, localityStats.getExecutionRowCount());
maxTime = localityStats.getExecutionMaxTime();
assertEquals(maxTime, sf.getStatistics().getQueryExecutionMaxTime());
// assertEquals( localities, stats.getQueryExecutionMaxTimeQueryString() );
tx.commit();
s.close();
assertFalse(s.isOpen());
// native sql queries
sf.getStatistics().clear();
s = sf.openSession();
tx = s.beginTransaction();
final String sql = "select id, name from Country";
results = s.createSQLQuery(sql).addEntity(Country.class).list().size();
QueryStatistics sqlStats = sf.getStatistics().getQueryStatistics(sql);
assertNotNull("sql stats were null", sqlStats);
assertEquals("unexpected execution count", 1, sqlStats.getExecutionCount());
assertEquals("unexpected row count", results, sqlStats.getExecutionRowCount());
maxTime = sqlStats.getExecutionMaxTime();
assertEquals(maxTime, sf.getStatistics().getQueryExecutionMaxTime());
// assertEquals( sql, stats.getQueryExecutionMaxTimeQueryString() );
tx.commit();
s.close();
s = sf.openSession();
tx = s.beginTransaction();
cleanDb(s);
tx.commit();
s.close();
sf.close();
}
use of org.hibernate.ScrollableResults in project querydsl by querydsl.
the class HibernateHandler method iterate.
@SuppressWarnings("unchecked")
@Override
public <T> CloseableIterator<T> iterate(Query query, FactoryExpression<?> projection) {
if (query instanceof HibernateQuery) {
HibernateQuery hQuery = (HibernateQuery) query;
ScrollableResults results = hQuery.getHibernateQuery().scroll(ScrollMode.FORWARD_ONLY);
CloseableIterator<T> iterator = new ScrollableResultsIterator<T>(results);
if (projection != null) {
iterator = new TransformingIterator<T>(iterator, projection);
}
return iterator;
} else {
Iterator<T> iterator = query.getResultList().iterator();
if (projection != null) {
return new TransformingIterator<T>(iterator, projection);
} else {
return new IteratorAdapter<T>(iterator);
}
}
}
use of org.hibernate.ScrollableResults in project uPortal by Jasig.
the class JpaPortalEventStore method aggregatePortalEvents.
@Override
@RawEventsTransactional
public boolean aggregatePortalEvents(DateTime startTime, DateTime endTime, int maxEvents, Function<PortalEvent, Boolean> handler) {
final Session session = this.getEntityManager().unwrap(Session.class);
session.setFlushMode(FlushMode.COMMIT);
final org.hibernate.Query query = session.createQuery(this.selectUnaggregatedQuery);
query.setParameter(this.startTimeParameter.getName(), startTime);
query.setParameter(this.endTimeParameter.getName(), endTime);
if (maxEvents > 0) {
query.setMaxResults(maxEvents);
}
int resultCount = 0;
for (final ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY); results.next(); ) {
final PersistentPortalEvent persistentPortalEvent = (PersistentPortalEvent) results.get(0);
final PortalEvent portalEvent;
try {
portalEvent = this.toPortalEvent(persistentPortalEvent.getEventData(), persistentPortalEvent.getEventType());
} catch (RuntimeException e) {
this.logger.warn("Failed to convert PersistentPortalEvent to PortalEvent: " + persistentPortalEvent, e);
//Mark the event as error and store the mark to prevent trying to reprocess the broken event data
persistentPortalEvent.setErrorAggregating(true);
session.persist(persistentPortalEvent);
continue;
}
try {
final Boolean eventHandled = handler.apply(portalEvent);
if (!eventHandled) {
this.logger.debug("Aggregation stop requested before processing event {}", portalEvent);
return false;
}
//Mark the event as aggregated and store the mark
persistentPortalEvent.setAggregated(true);
session.persist(persistentPortalEvent);
//periodic flush and clear of session to manage memory demands
if (++resultCount % this.flushPeriod == 0) {
this.logger.debug("Aggregated {} events, flush and clear {} EntityManager.", resultCount, BaseRawEventsJpaDao.PERSISTENCE_UNIT_NAME);
session.flush();
session.clear();
}
} catch (Exception e) {
this.logger.warn("Failed to aggregate portal event: " + persistentPortalEvent, e);
//mark the event as erred and move on. This will not be picked up by processing again
persistentPortalEvent.setErrorAggregating(true);
session.persist(persistentPortalEvent);
}
}
return true;
}
use of org.hibernate.ScrollableResults in project uPortal by Jasig.
the class JpaPortalEventStore method getPortalEvents.
@Override
public void getPortalEvents(DateTime startTime, DateTime endTime, int maxEvents, FunctionWithoutResult<PortalEvent> handler) {
final Session session = this.getEntityManager().unwrap(Session.class);
final org.hibernate.Query query = session.createQuery(this.selectQuery);
query.setParameter(this.startTimeParameter.getName(), startTime);
query.setParameter(this.endTimeParameter.getName(), endTime);
if (maxEvents > 0) {
query.setMaxResults(maxEvents);
}
for (final ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY); results.next(); ) {
final PersistentPortalEvent persistentPortalEvent = (PersistentPortalEvent) results.get(0);
final PortalEvent portalEvent = this.toPortalEvent(persistentPortalEvent.getEventData(), persistentPortalEvent.getEventType());
handler.apply(portalEvent);
persistentPortalEvent.setAggregated(true);
session.evict(persistentPortalEvent);
}
}
Aggregations