Java Code Examples for org.hibernate.ScrollableResults

The following examples show how to use org.hibernate.ScrollableResults. These examples are extracted from open source projects. 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
@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 2
@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 3
@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 4
/**
 * 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 5
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 6
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 7
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 8
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 9
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 10
@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 11
@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 12
Source Project: sailfish-core   Source File: MessageLoader.java    License: 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 13
Source Project: lams   Source File: CriteriaImpl.java    License: 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();
	}
}
 
Example 14
protected int getTotalNumber(Criteria criteria) {
	ScrollableResults results = criteria.scroll();
	results.last();
	int total = results.getRowNumber() + 1;
	results.close();
	return total;
}
 
Example 15
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 16
public ScrollableResults scroll(
		final QueryParameters queryParameters,
		final SessionImplementor session) throws HibernateException {		
	return scroll(
			queryParameters,
			resultTypes,
			getHolderInstantiator( queryParameters.getResultTransformer(), getReturnAliasesForTransformer() ),
			session
	);
}
 
Example 17
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 18
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 19
public ScrollableResults scroll(ScrollMode scrollMode) {
	before();
	try {
		return session.scroll(this, scrollMode);
	}
	finally {
		after();
	}
}
 
Example 20
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 21
/**
 * 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 22
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 23
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 24
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 25
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 26
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 27
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 28
Source Project: mamute   Source File: ModeratorsNewsletterJob.java    License: 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 29
Source Project: mamute   Source File: RegularUserNewsletterJob.java    License: 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 30
Source Project: mamute   Source File: NewsletterMailer.java    License: 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);
		}
	}

}