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

The following examples show how to use org.hibernate.ScrollableResults#get() . 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: 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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
Source File: ASTParserLoadingTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testDynamicInstantiationQueries() throws Exception {

		createTestBaseData();

		Session session = openSession();

		List results = session.createQuery( "select new Animal(an.description, an.bodyWeight) from Animal an" ).list();
		assertEquals( "Incorrect result size", 2, results.size() );
		assertClassAssignability( results.get( 0 ).getClass(), Animal.class );

		Iterator iter = session.createQuery( "select new Animal(an.description, an.bodyWeight) from Animal an" ).iterate();
		assertTrue( "Incorrect result size", iter.hasNext() );
		assertTrue( "Incorrect return type", iter.next() instanceof Animal );

		results = session.createQuery( "select new list(an.description, an.bodyWeight) from Animal an" ).list();
		assertEquals( "Incorrect result size", 2, results.size() );
		assertTrue( "Incorrect return type", results.get( 0 ) instanceof List );
		assertEquals( "Incorrect return type", ( (List) results.get( 0 ) ).size(), 2 );

		results = session.createQuery( "select new list(an.description, an.bodyWeight) from Animal an" ).list();
		assertEquals( "Incorrect result size", 2, results.size() );
		assertTrue( "Incorrect return type", results.get( 0 ) instanceof List );
		assertEquals( "Incorrect return type", ( (List) results.get( 0 ) ).size(), 2 );

		iter = session.createQuery( "select new list(an.description, an.bodyWeight) from Animal an" ).iterate();
		assertTrue( "Incorrect result size", iter.hasNext() );
		Object obj = iter.next();
		assertTrue( "Incorrect return type", obj instanceof List );
		assertEquals( "Incorrect return type", ( (List) obj ).size(), 2 );

		iter = ((org.hibernate.classic.Session)session).iterate( "select new list(an.description, an.bodyWeight) from Animal an" );
		assertTrue( "Incorrect result size", iter.hasNext() );
		obj = iter.next();
		assertTrue( "Incorrect return type", obj instanceof List );
		assertEquals( "Incorrect return type", ( (List) obj ).size(), 2 );

		results = session.createQuery( "select new map(an.description, an.bodyWeight) from Animal an" ).list();
		assertEquals( "Incorrect result size", 2, results.size() );
		assertTrue( "Incorrect return type", results.get( 0 ) instanceof Map );
		assertEquals( "Incorrect return type", ( (Map) results.get( 0 ) ).size(), 2 );
		assertTrue( ( (Map) results.get( 0 ) ).containsKey("0") );
		assertTrue( ( (Map) results.get( 0 ) ).containsKey("1") );

		results = session.createQuery( "select new map(an.description as descr, an.bodyWeight as bw) from Animal an" ).list();
		assertEquals( "Incorrect result size", 2, results.size() );
		assertTrue( "Incorrect return type", results.get( 0 ) instanceof Map );
		assertEquals( "Incorrect return type", ( (Map) results.get( 0 ) ).size(), 2 );
		assertTrue( ( (Map) results.get( 0 ) ).containsKey("descr") );
		assertTrue( ( (Map) results.get( 0 ) ).containsKey("bw") );

		iter = session.createQuery( "select new map(an.description, an.bodyWeight) from Animal an" ).iterate();
		assertTrue( "Incorrect result size", iter.hasNext() );
		obj = iter.next();
		assertTrue( "Incorrect return type", obj instanceof Map );
		assertEquals( "Incorrect return type", ( (Map) obj ).size(), 2 );

		ScrollableResults sr = session.createQuery( "select new map(an.description, an.bodyWeight) from Animal an" ).scroll();
		assertTrue( "Incorrect result size", sr.next() );
		obj = sr.get(0);
		assertTrue( "Incorrect return type", obj instanceof Map );
		assertEquals( "Incorrect return type", ( (Map) obj ).size(), 2 );
		sr.close();

		sr = session.createQuery( "select new Animal(an.description, an.bodyWeight) from Animal an" ).scroll();
		assertTrue( "Incorrect result size", sr.next() );
		assertTrue( "Incorrect return type", sr.get(0) instanceof Animal );
		sr.close();

		// caching...
		QueryStatistics stats = getSessions().getStatistics().getQueryStatistics( "select new Animal(an.description, an.bodyWeight) from Animal an" );
		results = session.createQuery( "select new Animal(an.description, an.bodyWeight) from Animal an" )
				.setCacheable( true )
				.list();
		assertEquals( "incorrect result size", 2, results.size() );
		assertClassAssignability( Animal.class, results.get( 0 ).getClass() );
		long initCacheHits = stats.getCacheHitCount();
		results = session.createQuery( "select new Animal(an.description, an.bodyWeight) from Animal an" )
				.setCacheable( true )
				.list();
		assertEquals( "dynamic intantiation query not served from cache", initCacheHits + 1, stats.getCacheHitCount() );
		assertEquals( "incorrect result size", 2, results.size() );
		assertClassAssignability( Animal.class, results.get( 0 ).getClass() );

		session.close();

		destroyTestBaseData();
	}
 
Example 11
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();
	}

}