org.hibernate.ScrollableResults Java Examples

The following examples show how to use org.hibernate.ScrollableResults. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CriteriaQueryTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testScrollCriteria() {
	Session session = openSession();
	Transaction t = session.beginTransaction();

	Course course = new Course();
	course.setCourseCode("HIB");
	course.setDescription("Hibernate Training");
	session.persist(course);
	session.flush();
	session.clear();
	ScrollableResults sr = session.createCriteria(Course.class).scroll();
	assertTrue( sr.next() );
	course = (Course) sr.get(0);
	assertNotNull(course);
	sr.close();
	session.delete(course);
	
	t.commit();
	session.close();
	
}
 
Example #2
Source File: HibernateSearch5InstrumentationTest.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Test
void performScrollLuceneIndexSearch() {
    try (ScrollableResults scroll = createNonJpaFullTextQuery(createQueryForDog1()).scroll()) {
        assertThat(scroll.next()).isTrue();

        assertAll(() -> {
            Object[] dogs = scroll.get();
            assertThat(dogs.length).isEqualTo(1);
            assertThat(((Dog) dogs[0]).getName()).isEqualTo("dog1");
            assertThat(scroll.isFirst()).isTrue();
            assertThat(scroll.isLast()).isTrue();

            assertApmSpanInformation(reporter, "name:dog1", "scroll");
        });
    }
}
 
Example #3
Source File: HQLTest.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void test_hql_api_scroll_projection_example() {
	doInJPA( this::entityManagerFactory, entityManager -> {
		Session session = entityManager.unwrap( Session.class );
		//tag::hql-api-scroll-example[]
		try ( ScrollableResults scrollableResults = session.createQuery(
				"select p " +
				"from Person p " +
				"where p.name like :name" )
				.setParameter( "name", "J%" )
				.scroll()
		) {
			while(scrollableResults.next()) {
				Person person = (Person) scrollableResults.get()[0];
				process(person);
			}
		}
		//end::hql-api-scroll-example[]
	});
}
 
Example #4
Source File: CollectionRepositoryImpl.java    From AIDR with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Long getStoppedCollectionsCount(String terms) {
	Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
	criteria.setProjection(Projections.projectionList()
			.add(Projections.property("id"), "id"));
	
	LogicalExpression or = Restrictions.or(
			Restrictions.eq("status", CollectionStatus.STOPPED),
			Restrictions.eq("status", CollectionStatus.NOT_RUNNING)
			);
	
	LogicalExpression orAll = Restrictions.or(
			or,
			Restrictions.eq("status", CollectionStatus.FATAL_ERROR)
			);
	
	criteria.add(orAll);
	addCollectionSearchCriteria(terms, criteria);

	ScrollableResults scroll = criteria.scroll();
	int i = scroll.last() ? scroll.getRowNumber() + 1 : 0;
	return Long.valueOf(i);
}
 
Example #5
Source File: HQLTest.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void test_hql_api_scroll_open_example() {
	ScrollableResults scrollableResults = doInJPA( this::entityManagerFactory, entityManager -> {
		Session session = entityManager.unwrap( Session.class );
		return session.createQuery(
			"select p " +
			"from Person p " +
			"where p.name like :name" )
		.setParameter( "name", "J%" )
		.scroll();
	});
	try {
		scrollableResults.next();
		fail("Should throw exception because the ResultSet must be closed by now!");
	}
	catch ( Exception expected ) {
	}
}
 
Example #6
Source File: FooPaginationPersistenceIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public final void givenUsingTheScrollableApi_whenRetrievingPaginatedData_thenCorrect() {
    final int pageSize = 10;
    final String hql = "FROM Foo f order by f.name";
    final Query query = session.createQuery(hql);

    final ScrollableResults resultScroll = query.scroll(ScrollMode.FORWARD_ONLY);

    // resultScroll.last();
    // final int totalResults = resultScroll.getRowNumber() + 1;

    resultScroll.first();
    resultScroll.scroll(0);
    final List<Foo> fooPage = Lists.newArrayList();
    int i = 0;
    while (pageSize > i++) {
        fooPage.add((Foo) resultScroll.get(0));
        if (!resultScroll.next()) {
            break;
        }
    }

    assertThat(fooPage, hasSize(lessThan(10 + 1)));
}
 
Example #7
Source File: JRHibernateQueryExecuter.java    From jasperreports with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Runs the query by calling <code>org.hibernate.Query.scroll()</code>.
 * 
 * @return scrollable results of the query
 */
public ScrollableResults scroll()
{
	setMaxCount();
	
	setQueryRunning(true);
	try
	{
		scrollableResults = query.scroll(ScrollMode.FORWARD_ONLY);
	}
	finally
	{
		setQueryRunning(false);
	}
	
	return scrollableResults;
}
 
Example #8
Source File: HQLQueryPlan.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public ScrollableResults performScroll(
		QueryParameters queryParameters,
        SessionImplementor session) throws HibernateException {
	if ( log.isTraceEnabled() ) {
		log.trace( "iterate: " + getSourceQuery() );
		queryParameters.traceParameters( session.getFactory() );
	}
	if ( translators.length != 1 ) {
		throw new QueryException( "implicit polymorphism not supported for scroll() queries" );
	}
	if ( queryParameters.getRowSelection().definesLimits() && translators[0].containsCollectionFetches() ) {
		throw new QueryException( "firstResult/maxResults not supported in conjunction with scroll() of a query containing collection fetches" );
	}

	return translators[0].scroll( queryParameters, session );
}
 
Example #9
Source File: SessionImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public ScrollableResults scroll(CriteriaImpl criteria, ScrollMode scrollMode) {
	errorIfClosed();
	checkTransactionSynchStatus();
	String entityName = criteria.getEntityOrClassName();
	CriteriaLoader loader = new CriteriaLoader(
			getOuterJoinLoadable(entityName),
			factory,
			criteria,
			entityName,
			getEnabledFilters()
	);
	autoFlushIfRequired( loader.getQuerySpaces() );
	dontFlushFromFind++;
	try {
		return loader.scroll(this, scrollMode);
	}
	finally {
		dontFlushFromFind--;
	}
}
 
Example #10
Source File: SessionImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public ScrollableResults scrollCustomQuery(CustomQuery customQuery, QueryParameters queryParameters) 
throws HibernateException {
	errorIfClosed();
	checkTransactionSynchStatus();

	if ( log.isTraceEnabled() ) {
		log.trace( "scroll SQL query: " + customQuery.getSQL() );
	}

	CustomLoader loader = new CustomLoader( customQuery, getFactory() );

	autoFlushIfRequired( loader.getQuerySpaces() );

	dontFlushFromFind++; //stops flush being called multiple times if this method is recursively called
	try {
		return loader.scroll(queryParameters, this);
	}
	finally {
		dontFlushFromFind--;
	}
}
 
Example #11
Source File: SQLQueryImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public ScrollableResults scroll(ScrollMode scrollMode) throws HibernateException {
	verifyParameters();
	before();

	Map namedParams = getNamedParams();
	NativeSQLQuerySpecification spec = generateQuerySpecification( namedParams );

	QueryParameters qp = getQueryParameters( namedParams );
	qp.setScrollMode( scrollMode );

	try {
		return getSession().scroll( spec, qp );
	}
	finally {
		after();
	}
}
 
Example #12
Source File: ModeratorsNewsletterJob.java    From mamute with Apache License 2.0 5 votes vote down vote up
@Override
public void execute() {
	LOG.info("executing " + getClass().getSimpleName());
	if (env.supports("feature.newsletter")) {
		LOG.info("sending newsletter emails");
		ScrollableResults results = users.moderators();
		newsMailer.sendTo(results, true);
		result.notFound();
	}
}
 
Example #13
Source File: MarketOrderDAOImpl.java    From computational-economy with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Iterator<MarketOrder> getIterator(final Currency currency, final Currency commodityCurrency) {
	final String queryString = "FROM MarketOrderImpl m "
			+ "WHERE m.currency = :currency AND m.commodityCurrency = :commodityCurrency "
			+ "ORDER BY m.pricePerUnit ASC";
	final ScrollableResults itemCursor = getSession().createQuery(queryString).setParameter("currency", currency)
			.setParameter("commodityCurrency", commodityCurrency).scroll(ScrollMode.FORWARD_ONLY);
	return new HibernateIteratorImpl<MarketOrder>(itemCursor);
}
 
Example #14
Source File: NewsletterMailer.java    From mamute with Apache License 2.0 5 votes vote down vote up
public void sendTo(ScrollableResults results, boolean isTestNewsletter) {
	DateTime pastWeek = new DateTime().minusWeeks(1);
	DateTime twelveHoursAgo = new DateTime().minusHours(12);
	List<News> hotNews = news.hotNews();
	List<Question> hotQuestions = questions.hot(pastWeek, 8);
	List<Question> unanswered = questions.randomUnanswered(pastWeek, twelveHoursAgo, 8);
	LinkToHelper linkToHelper = new NotificationMailer.LinkToHelper(router, brutalEnv);
	String siteName = bundle.getMessage("site.name");
	String date = brutalDateFormat.getInstance("date.joda.newsletter.pattern").print(new DateTime());
	
	String teste = isTestNewsletter ? bundle.getMessage("newsletter_mail_test") : "";
	
	while (results.next()) {
		User user = (User) results.get()[0];
		try {
			Email email = templates.template("newsletter_mail", date, siteName, teste)
					.with("hotNews", hotNews)
					.with("hotQuestions", hotQuestions)
					.with("unansweredQuestions", unanswered)
					.with("unsubscribeLink", linkToHelper.unsubscribeLink(user))
					.with("linkToHelper", linkToHelper)
					.with("l10n", bundle)
					.with("sanitizer", POLICY)
					.with("siteName", siteName)
					.with("date", date)
					.with("logoUrl", env.get("mail_logo_url"))
					.to(user.getName(), user.getEmail());
			email.setCharset("utf-8");
			mailer.send(email);
		} catch (Exception e) {
			LOG.error("could not send email", e);
		}
	}

}
 
Example #15
Source File: RegularUserNewsletterJob.java    From mamute with Apache License 2.0 5 votes vote down vote up
@Override
@Path("/wjh1jkh34jk12hkjehd13kj4h1kjh41jkhwe12341")
public void execute() {
	LOG.info("executing " + getClass().getSimpleName());
	if (shouldSendNewsletter()) {
		LOG.info("sending newsletter emails");
		ScrollableResults results = users.newsletterConfirmed();
		newsMailer.sendTo(results, false);
		newsletterSentLogs.saveLog();
		result.notFound();
	}
}
 
Example #16
Source File: AbstractHibernateDAO.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
protected int getTotalNumber(Criteria criteria) {
	ScrollableResults results = criteria.scroll();
	results.last();
	int total = results.getRowNumber() + 1;
	results.close();
	return total;
}
 
Example #17
Source File: ScrollableCollectionFetchingTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testScrollingJoinFetchesPositioning() {
	TestData data = new TestData();
	data.prepare();

	Session s = openSession();
	Transaction txn = s.beginTransaction();

	ScrollableResults results = s
	        .createQuery( "from Animal a left join fetch a.offspring where a.description like :desc order by a.id" )
	        .setString( "desc", "root%" )
	        .scroll();

	results.first();
	Animal animal = ( Animal ) results.get( 0 );
	assertEquals( "first() did not return expected row", data.root1Id, animal.getId() );

	results.scroll( 1 );
	animal = ( Animal ) results.get( 0 );
	assertEquals( "scroll(1) did not return expected row", data.root2Id, animal.getId() );

	results.scroll( -1 );
	animal = ( Animal ) results.get( 0 );
	assertEquals( "scroll(-1) did not return expected row", data.root1Id, animal.getId() );

	results.setRowNumber( 1 );
	animal = ( Animal ) results.get( 0 );
	assertEquals( "setRowNumber(1) did not return expected row", data.root1Id, animal.getId() );

	results.setRowNumber( 2 );
	animal = ( Animal ) results.get( 0 );
	assertEquals( "setRowNumber(2) did not return expected row", data.root2Id, animal.getId() );

	txn.commit();
	s.close();

	data.cleanup();
}
 
Example #18
Source File: SessionImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public ScrollableResults scroll(String query, QueryParameters queryParameters) throws HibernateException {
	errorIfClosed();
	checkTransactionSynchStatus();
	HQLQueryPlan plan = getHQLQueryPlan( query, false );
	autoFlushIfRequired( plan.getQuerySpaces() );
	dontFlushFromFind++;
	try {
		return plan.performScroll( queryParameters, this );
	}
	finally {
		dontFlushFromFind--;
	}
}
 
Example #19
Source File: MessageLoader.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
public MessageLoader(ScrollableResults results, Session session) {
    this.results = results;
    this.session = session;
    results.last();
    numberOfRecords = results.getRowNumber() + 1;
    results.beforeFirst();
}
 
Example #20
Source File: HQLDataSet.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private int getResultNumberUsingScrollableResults(org.hibernate.Query hibernateQuery, Session session) {
	int resultNumber = 0;
	logger.debug("Scrolling query " + statement.getQueryString() + " ...");
	ScrollableResults scrollableResults = hibernateQuery.scroll();
	scrollableResults.last();
	logger.debug("Scrolled query " + statement.getQueryString());
	resultNumber = scrollableResults.getRowNumber() + 1; // Hibernate ScrollableResults row number starts with 0
	logger.debug("Number of fetched records: " + resultNumber + " for query " + statement.getQueryString());
	resultNumber = resultNumber < 0 ? 0 : resultNumber;
	return resultNumber;
}
 
Example #21
Source File: ScrollableCollectionFetchingTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testScrollingJoinFetchesReverse() {
	TestData data = new TestData();
	data.prepare();

	Session s = openSession();
	Transaction txn = s.beginTransaction();

	ScrollableResults results = s
	        .createQuery( "from Animal a left join fetch a.offspring where a.description like :desc order by a.id" )
	        .setString( "desc", "root%" )
	        .scroll();

	results.afterLast();

	int counter = 0;
	while ( results.previous() ) {
		counter++;
		Animal animal = ( Animal ) results.get( 0 );
		checkResult( animal );
	}
	assertEquals( "unexpected result count", 2, counter );

	txn.commit();
	s.close();

	data.cleanup();
}
 
Example #22
Source File: ScrollableCollectionFetchingTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testScrollingJoinFetchesForward() {
	if ( ! supportsResultSetPositionQueryMethodsOnForwardOnlyCursor() ) {
		return;
	}

	TestData data = new TestData();
	data.prepare();

	Session s = openSession();
	Transaction txn = s.beginTransaction();

	ScrollableResults results = s
	        .createQuery( "from Animal a left join fetch a.offspring where a.description like :desc order by a.id" )
	        .setString( "desc", "root%" )
			.scroll( ScrollMode.FORWARD_ONLY );

	int counter = 0;
	while ( results.next() ) {
		counter++;
		Animal animal = ( Animal ) results.get( 0 );
		checkResult( animal );
	}
	assertEquals( "unexpected result count", 2, counter );

	txn.commit();
	s.close();

	data.cleanup();
}
 
Example #23
Source File: QueryImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public ScrollableResults scroll(ScrollMode scrollMode) throws HibernateException {
	verifyParameters();
	Map namedParams = getNamedParams();
	before();
	QueryParameters qp = getQueryParameters(namedParams);
	qp.setScrollMode(scrollMode);
	try {
		return getSession().scroll( expandParameterLists(namedParams), qp );
	}
	finally {
		after();
	}
}
 
Example #24
Source File: CriteriaImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public ScrollableResults scroll(ScrollMode scrollMode) {
	before();
	try {
		return session.scroll(this, scrollMode);
	}
	finally {
		after();
	}
}
 
Example #25
Source File: IterateTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testScroll() throws Exception {
	getSessions().getStatistics().clear();
	Session s = openSession();
	Transaction t = s.beginTransaction();
	Item i1 = new Item("foo");
	Item i2 = new Item("bar");
	s.persist("Item", i1);
	s.persist("Item", i2);
	t.commit();
	s.close();

	s = openSession();
	t = s.beginTransaction();
	ScrollableResults sr = s.getNamedQuery("Item.nameDesc").scroll();
	assertTrue( sr.next() );
	i1 = (Item) sr.get(0);
	assertTrue( sr.next() );
	i2 = (Item) sr.get(0);
	assertTrue( Hibernate.isInitialized(i1) );
	assertTrue( Hibernate.isInitialized(i2) );
	assertEquals( i1.getName(), "foo" );
	assertEquals( i2.getName(), "bar" );
	assertFalse( sr.next() );
	s.delete(i1);
	s.delete(i2);
	t.commit();
	s.close();
	assertEquals( getSessions().getStatistics().getEntityFetchCount(), 0 );
}
 
Example #26
Source File: AggressiveReleaseTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testQueryScrolling() throws Throwable {
	prepare();
	Session s = getSessionUnderTest();
	Silly silly = new Silly( "silly" );
	s.save( silly );
	s.flush();

	ScrollableResults sr = s.createQuery( "from Silly" ).scroll();
	assertTrue( sr.next() );
	Silly silly2 = ( Silly ) sr.get( 0 );
	assertEquals( silly, silly2 );
	sr.close();

	sr = s.createQuery( "from Silly" ).scroll();
	ScrollableResults sr2 = s.createQuery( "from Silly where name = 'silly'" ).scroll();

	assertTrue( sr.next() );
	assertEquals( silly, sr.get( 0 ) );
	assertTrue( sr2.next() );
	assertEquals( silly, sr2.get( 0 ) );

	sr.close();
	sr2.close();

	s.delete( silly );
	s.flush();

	release( s );
	done();
}
 
Example #27
Source File: StatelessSessionImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public ScrollableResults scroll(CriteriaImpl criteria, ScrollMode scrollMode) {
	errorIfClosed();
	String entityName = criteria.getEntityOrClassName();
	CriteriaLoader loader = new CriteriaLoader(
			getOuterJoinLoadable(entityName),
	        factory,
	        criteria,
	        entityName,
	        getEnabledFilters()
		);
	return loader.scroll(this, scrollMode);
}
 
Example #28
Source File: AggressiveReleaseTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testSerializationFailsOnAfterStatementAggressiveReleaseWithOpenResources() throws Throwable {
	prepare();
	Session s = getSessionUnderTest();

	Silly silly = new Silly( "silly" );
	s.save( silly );

	// this should cause the CM to obtain a connection, and then release it
	s.flush();

	// both scroll() and iterate() cause the batcher to hold on
	// to resources, which should make aggresive-release not release
	// the connection (and thus cause serialization to fail)
	ScrollableResults sr = s.createQuery( "from Silly" ).scroll();

	try {
		SerializationHelper.serialize( s );
		fail( "Serialization allowed on connected session; or aggressive release released connection with open resources" );
	}
	catch( IllegalStateException e ) {
		// expected behavior
	}

	// Closing the ScrollableResults does currently force the batcher to
	// aggressively release the connection
	sr.close();
	SerializationHelper.serialize( s );

	s.delete( silly );
	s.flush();

	release( s );
	done();
}
 
Example #29
Source File: QueryTranslatorImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Return the query results, as an instance of <tt>ScrollableResults</tt>
 */
public ScrollableResults scroll(QueryParameters queryParameters, SessionImplementor session)
		throws HibernateException {
	// Delegate to the QueryLoader...
	errorIfDML();
	return queryLoader.scroll( queryParameters, session );
}
 
Example #30
Source File: CriteriaImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public ScrollableResults scroll(ScrollMode scrollMode) {
	before();
	try {
		return session.scroll(this, scrollMode);
	}
	finally {
		after();
	}
}