Java Code Examples for org.hibernate.ScrollableResults#next()

The following examples show how to use org.hibernate.ScrollableResults#next() . 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: 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 2
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 3
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 4
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 5
Source File: IndexHelper.java    From document-management-system with GNU General Public License v2.0 4 votes vote down vote up
protected int doRebuildIndex() throws Exception {
	FullTextSession fullTextSession = (FullTextSession) entityManager.getDelegate();
	fullTextSession.setFlushMode(org.hibernate.FlushMode.MANUAL);
	fullTextSession.setCacheMode(org.hibernate.CacheMode.IGNORE);
	fullTextSession.purgeAll(NodeDocumentVersion.class);
	fullTextSession.getSearchFactory().optimize(NodeDocumentVersion.class);

	String query = "select ndv from NodeDocumentVersion 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;
		cursor.first(); // Reset to first result row
		int i = 0;

		while (true) {
			fullTextSession.index(cursor.get(0));

			if (++i % batchSize == 0) {
				fullTextSession.flushToIndexes();
				fullTextSession.clear(); // Clear persistence context for each batch
				log.info("Flushed index update " + i + " from Thread "
						+ Thread.currentThread().getName());
			}

			if (cursor.isLast()) {
				break;
			}

			cursor.next();
		}
	}

	cursor.close();
	fullTextSession.flushToIndexes();
	fullTextSession.clear(); // Clear persistence context for each batch
	fullTextSession.getSearchFactory().optimize(NodeDocumentVersion.class);

	return count;
}
 
Example 6
Source File: CMTTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testCurrentSessionWithScroll() throws Exception {
	DummyTransactionManager.INSTANCE.begin();
	Session s = getSessions().getCurrentSession();
	Map item1 = new HashMap();
	item1.put( "name", "Item - 1" );
	item1.put( "description", "The first item" );
	s.persist( "Item", item1 );

	Map item2 = new HashMap();
	item2.put( "name", "Item - 2" );
	item2.put( "description", "The second item" );
	s.persist( "Item", item2 );
	DummyTransactionManager.INSTANCE.getTransaction().commit();

	// First, test partially scrolling the result with out closing
	DummyTransactionManager.INSTANCE.begin();
	s = getSessions().getCurrentSession();
	ScrollableResults results = s.createQuery( "from Item" ).scroll();
	results.next();
	DummyTransactionManager.INSTANCE.getTransaction().commit();

	// Next, test partially scrolling the result with closing
	DummyTransactionManager.INSTANCE.begin();
	s = getSessions().getCurrentSession();
	results = s.createQuery( "from Item" ).scroll();
	results.next();
	results.close();
	DummyTransactionManager.INSTANCE.getTransaction().commit();

	// Next, scroll the entire result (w/o closing)
	DummyTransactionManager.INSTANCE.begin();
	s = getSessions().getCurrentSession();
	results = s.createQuery( "from Item" ).scroll();
	while ( !results.isLast() ) {
		results.next();
	}
	DummyTransactionManager.INSTANCE.getTransaction().commit();

	// Next, scroll the entire result (closing)
	DummyTransactionManager.INSTANCE.begin();
	s = getSessions().getCurrentSession();
	results = s.createQuery( "from Item" ).scroll();
	while ( !results.isLast() ) {
		results.next();
	}
	results.close();
	DummyTransactionManager.INSTANCE.getTransaction().commit();

	DummyTransactionManager.INSTANCE.begin();
	s = getSessions().getCurrentSession();
	s.createQuery( "delete from Item" ).executeUpdate();
	DummyTransactionManager.INSTANCE.getTransaction().commit();
}
 
Example 7
Source File: FooBarTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testScrollableIterator() throws Exception {
	if ( getDialect() instanceof DB2Dialect || getDialect() instanceof OracleDialect || getDialect() instanceof SybaseDialect || getDialect() instanceof HSQLDialect ) {
		Session s = openSession();
		Transaction txn = s.beginTransaction();
		s.save( new Foo() );
		s.save( new Foo() );
		s.save( new Foo() );
		s.save( new Bar() );
		Query query = s.createQuery("select f, f.integer from Foo f");
		assertTrue( query.getReturnTypes().length==2 );
		ScrollableResults iter = query.scroll();
		assertTrue( iter.next() );
		assertTrue( iter.scroll(1) );
		FooProxy f2 = (FooProxy) iter.get()[0];
		assertTrue( f2!=null );
		assertTrue( iter.scroll(-1) );
		Object f1 = iter.get(0);
		iter.next();
		assertTrue( f1!=null && iter.get(0)==f2 );
		iter.getInteger(1);

		assertTrue( !iter.scroll(100) );
		assertTrue( iter.first() );
		assertTrue( iter.scroll(3) );
		Object f4 = iter.get(0);
		assertTrue( f4!=null );
		assertTrue( !iter.next() );
		assertTrue( iter.first() );
		assertTrue( iter.get(0)==f1 );
		assertTrue( iter.last() );
		assertTrue( iter.get(0)==f4 );
		assertTrue( iter.previous() );
		txn.commit();
		s.close();

		s = openSession();
		txn = s.beginTransaction();
		query = s.createQuery("select f, f.integer from Foo f");
		assertTrue( query.getReturnTypes().length==2 );
		iter = query.scroll();
		assertTrue( iter.next() );
		assertTrue( iter.scroll(1) );
		f2 = (FooProxy) iter.get()[0];
		assertTrue( f2!=null );
		assertTrue( f2.getString()!=null  && f2.getComponent().getImportantDates().length > 0 );
		assertTrue( iter.scroll(-1) );
		f1 = iter.get(0);
		iter.next();
		assertTrue( f1!=null && iter.get(0)==f2 );
		iter.getInteger(1);

		assertTrue( !iter.scroll(100) );
		assertTrue( iter.first() );
		assertTrue( iter.scroll(3) );
		f4 = iter.get(0);
		assertTrue( f4!=null );
		assertTrue( !iter.next() );
		assertTrue( iter.first() );
		assertTrue( iter.get(0)==f1 );
		assertTrue( iter.last() );
		assertTrue( iter.get(0)==f4 );
		assertTrue( iter.previous() );
		assertTrue( s.delete("from Foo")==4 );
		s.flush();
		assertTrue( s.find("from java.lang.Object").size()==0 );
		txn.commit();
		s.close();
	}
}
 
Example 8
Source File: StatelessSessionTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testCreateUpdateReadDelete() {
	StatelessSession ss = getSessions().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();

}
 
Example 9
Source File: LuceneContentDaoImpl.java    From Lottery with GNU General Public License v2.0 4 votes vote down vote up
public Integer index(IndexWriter writer, Integer siteId, Integer channelId,
		Date startDate, Date endDate, Integer startId, Integer max)
		throws CorruptIndexException, IOException {
	Finder f = Finder.create("select bean from Content bean");
	if (channelId != null) {
		f.append(" join bean.channel channel, Channel parent");
		f.append(" where channel.lft between parent.lft and parent.rgt");
		f.append(" and channel.site.id=parent.site.id");
		f.append(" and parent.id=:parentId");
		f.setParam("parentId", channelId);
	} else if (siteId != null) {
		f.append(" where bean.site.id=:siteId");
		f.setParam("siteId", siteId);
	} else {
		f.append(" where 1=1");
	}
	if (startId != null) {
		f.append(" and bean.id > :startId");
		f.setParam("startId", startId);
	}
	if (startDate != null) {
		f.append(" and bean.contentExt.releaseDate >= :startDate");
		f.setParam("startDate", startDate);
	}
	if (endDate != null) {
		f.append(" and bean.contentExt.releaseDate <= :endDate");
		f.setParam("endDate", endDate);
	}
	f.append(" and bean.status=" + ContentCheck.CHECKED);
	f.append(" order by bean.id asc");
	if (max != null) {
		f.setMaxResults(max);
	}
	Session session = getSession();
	ScrollableResults contents = f.createQuery(getSession()).setCacheMode(
			CacheMode.IGNORE).scroll(ScrollMode.FORWARD_ONLY);
	int count = 0;
	Content content = null;
	while (contents.next()) {
		content = (Content) contents.get(0);
		writer.addDocument(LuceneContent.createDocument(content));
		if (++count % 20 == 0) {
			session.clear();
		}
	}
	if (count < max || content == null) {
		// 实际数量小于指定数量,代表生成结束。如果没有任何数据,也代表生成结束。
		return null;
	} else {
		// 返回最后一个ID
		return content.getId();
	}

}