org.hibernate.ScrollMode Java Examples

The following examples show how to use org.hibernate.ScrollMode. 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: SessionImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public ScrollableResultsImplementor scroll(Criteria criteria, ScrollMode scrollMode) {
	// TODO: Is this guaranteed to always be CriteriaImpl?
	CriteriaImpl criteriaImpl = (CriteriaImpl) criteria;

	checkOpenOrWaitingForAutoClose();
	checkTransactionSynchStatus();

	String entityName = criteriaImpl.getEntityOrClassName();
	CriteriaLoader loader = new CriteriaLoader(
			getOuterJoinLoadable( entityName ),
			getFactory(),
			criteriaImpl,
			entityName,
			getLoadQueryInfluencers()
	);
	autoFlushIfRequired( loader.getQuerySpaces() );
	dontFlushFromFind++;
	try {
		return loader.scroll( this, scrollMode );
	}
	finally {
		delayedAfterCompletion();
		dontFlushFromFind--;
	}
}
 
Example #2
Source File: SpringHibernateDataStore.java    From elide-spring-boot with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Constructor.</p>
 * Useful for extending the store and relying on existing code
 * to instantiate custom hibernate transaction.
 *
 * @param txManager Spring PlatformTransactionManager
 * @param beanFactory Spring AutowireCapableBeanFactory
 * @param entityManager EntityManager factory
 * @param isScrollEnabled Whether or not scrolling is enabled on driver
 * @param scrollMode Scroll mode to use for scrolling driver
 * @param transactionSupplier Supplier for transaction
 */
protected SpringHibernateDataStore(PlatformTransactionManager txManager,
    AutowireCapableBeanFactory beanFactory,
    EntityManager entityManager,
    ElideProperties elideProperties,
    boolean isScrollEnabled,
    ScrollMode scrollMode,
    HibernateTransactionSupplier transactionSupplier) {
  this.txManager = txManager;
  this.beanFactory = beanFactory;
  this.entityManager = entityManager;
  this.elideProperties = elideProperties;
  this.isScrollEnabled = isScrollEnabled;
  this.scrollMode = scrollMode;
  this.transactionSupplier = transactionSupplier;
}
 
Example #3
Source File: StatelessSessionImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public ScrollableResultsImplementor scroll(Criteria criteria, ScrollMode scrollMode) {
	// TODO: Is this guaranteed to always be CriteriaImpl?
	CriteriaImpl criteriaImpl = (CriteriaImpl) criteria;

	checkOpen();
	String entityName = criteriaImpl.getEntityOrClassName();
	CriteriaLoader loader = new CriteriaLoader(
			getOuterJoinLoadable( entityName ),
			getFactory(),
			criteriaImpl,
			entityName,
			getLoadQueryInfluencers()
	);
	return loader.scroll( this, scrollMode );
}
 
Example #4
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 #5
Source File: Loader.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private ScrollMode getScrollMode(
		boolean scroll,
		boolean hasFirstRow,
		boolean useLimitOffSet,
		QueryParameters queryParameters) {
	final boolean canScroll = getFactory().getSessionFactoryOptions().isScrollableResultSetsEnabled();
	if ( canScroll ) {
		if ( scroll ) {
			return queryParameters.getScrollMode();
		}
		if ( hasFirstRow && !useLimitOffSet ) {
			return ScrollMode.SCROLL_INSENSITIVE;
		}
	}
	return null;
}
 
Example #6
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 #7
Source File: AbstractBatcher.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public PreparedStatement prepareQueryStatement(
		String sql,
        boolean scrollable,
        ScrollMode scrollMode) throws SQLException, HibernateException {
	logOpenPreparedStatement();
	PreparedStatement ps = getPreparedStatement(
			connectionManager.getConnection(),
	        sql,
	        scrollable,
	        scrollMode
	);
	setStatementFetchSize( ps );
	statementsToClose.add( ps );
	lastQuery = ps;
	return ps;
}
 
Example #8
Source File: AbstractBatcher.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public CallableStatement prepareCallableQueryStatement(
		String sql,
        boolean scrollable,
        ScrollMode scrollMode) throws SQLException, HibernateException {
	logOpenPreparedStatement();
	CallableStatement ps = ( CallableStatement ) getPreparedStatement(
			connectionManager.getConnection(),
	        sql,
	        scrollable,
	        false,
	        null,
	        scrollMode,
	        true
	);
	setStatementFetchSize( ps );
	statementsToClose.add( ps );
	lastQuery = ps;
	return ps;
}
 
Example #9
Source File: AbstractBatcher.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private PreparedStatement getPreparedStatement(
		final Connection conn,
        final String sql,
        final boolean scrollable,
        final ScrollMode scrollMode)
throws SQLException {
	return getPreparedStatement(
			conn,
	        sql,
	        scrollable,
	        false,
	        null,
	        scrollMode,
	        false
	);
}
 
Example #10
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 #11
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 #12
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 #13
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();
	}
}
 
Example #14
Source File: SpringHibernateDataStore.java    From elide-spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param txManager Spring PlatformTransactionManager
 * @param beanFactory Spring AutowireCapableBeanFactory
 * @param entityManager EntityManager
 * @param isScrollEnabled Whether or not scrolling is enabled on driver
 * @param scrollMode Scroll mode to use for scrolling driver
 */
public SpringHibernateDataStore(PlatformTransactionManager txManager,
    AutowireCapableBeanFactory beanFactory,
    EntityManager entityManager,
    ElideProperties elideProperties,
    boolean isScrollEnabled,
    ScrollMode scrollMode) {
  this(txManager, beanFactory, entityManager, elideProperties,
      isScrollEnabled, scrollMode, SpringHibernateTransaction::new);
}
 
Example #15
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 #16
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 #17
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 #18
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 Class<? extends Property> propertyClass) {
	final String queryString = "FROM MarketOrderImpl m "
			+ "WHERE m.currency = :currency AND m.property.class = :propertyClass " + "ORDER BY m.pricePerUnit ASC";
	final ScrollableResults itemCursor = getSession().createQuery(queryString).setParameter("currency", currency)
			.setParameter("propertyClass", propertyClass.getSimpleName()).scroll(ScrollMode.FORWARD_ONLY);
	return new HibernateIteratorImpl<MarketOrder>(itemCursor);
}
 
Example #19
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 #20
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 GoodType goodType) {
	final String queryString = "FROM MarketOrderImpl m "
			+ "WHERE m.currency = :currency AND m.goodType = :goodType " + "ORDER BY m.pricePerUnit ASC";
	final ScrollableResults itemCursor = getSession().createQuery(queryString).setParameter("currency", currency)
			.setParameter("goodType", goodType).scroll(ScrollMode.FORWARD_ONLY);
	return new HibernateIteratorImpl<MarketOrder>(itemCursor);
}
 
Example #21
Source File: SpringHibernateTransaction.java    From elide-spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param session Hibernate session
 * @param txManager Spring PlatformTransactionManager
 * @param txStatus Spring Transaction status
 * @param isScrollEnabled Whether or not scrolling is enabled
 * @param scrollMode Scroll mode to use if scrolling enabled
 */
protected SpringHibernateTransaction(Session session,
    PlatformTransactionManager txManager,
    TransactionStatus txStatus,
    boolean isScrollEnabled,
    ScrollMode scrollMode) {
  super(session, isScrollEnabled, scrollMode);
  this.session = session;
  this.txManager = txManager;
  this.txStatus = txStatus;
}
 
Example #22
Source File: NativeQueryImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected ScrollableResultsImplementor doScroll(ScrollMode scrollMode) {
	final NativeSQLQuerySpecification nativeSQLQuerySpecification = generateQuerySpecification();
	final QueryParameters queryParameters = getQueryParameters();
	queryParameters.setScrollMode( scrollMode );
	return getProducer().scroll(
			nativeSQLQuerySpecification,
			queryParameters
	);
}
 
Example #23
Source File: AbstractLoadPlanBasedLoader.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected ScrollMode getScrollMode(boolean scroll, boolean hasFirstRow, boolean useLimitOffSet, QueryParameters queryParameters) {
	final boolean canScroll = getFactory().getSettings().isScrollableResultSetsEnabled();
	if ( canScroll ) {
		if ( scroll ) {
			return queryParameters.getScrollMode();
		}
		if ( hasFirstRow && !useLimitOffSet ) {
			return ScrollMode.SCROLL_INSENSITIVE;
		}
	}
	return null;
}
 
Example #24
Source File: AbstractProducedQuery.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public ScrollableResultsImplementor scroll(ScrollMode scrollMode) {
	beforeQuery();
	try {
		return doScroll( scrollMode );
	}
	finally {
		afterQuery();
	}
}
 
Example #25
Source File: AbstractProducedQuery.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected ScrollableResultsImplementor doScroll(ScrollMode scrollMode) {
	if (getMaxResults() == 0){
		return EmptyScrollableResults.INSTANCE;
	}
	final String query = getQueryParameterBindings().expandListValuedParameters( getQueryString(), getProducer() );
	QueryParameters queryParameters = makeQueryParametersForExecution( query );
	queryParameters.setScrollMode( scrollMode );
	return getProducer().scroll( query, queryParameters );
}
 
Example #26
Source File: CriteriaLoader.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public ScrollableResultsImplementor scroll(SharedSessionContractImplementor session, ScrollMode scrollMode)
throws HibernateException {
	QueryParameters qp = translator.getQueryParameters();
	qp.setScrollMode(scrollMode);
	return scroll(qp, resultTypes, null, session);
}
 
Example #27
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();
	}

}
 
Example #28
Source File: AbstractProxySharedSessionContractImplementor.java    From jadira with Apache License 2.0 4 votes vote down vote up
@Override
public ScrollableResultsImplementor scroll(Criteria criteria, ScrollMode scrollMode) {
	return target.scroll(criteria, scrollMode);
}
 
Example #29
Source File: Loader.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Obtain a <tt>PreparedStatement</tt> with all parameters pre-bound.
 * Bind JDBC-style <tt>?</tt> parameters, named parameters, and
 * limit parameters.
 */
protected final PreparedStatement prepareQueryStatement(
		String sql,
		final QueryParameters queryParameters,
		final LimitHandler limitHandler,
		final boolean scroll,
		final SharedSessionContractImplementor session) throws SQLException, HibernateException {
	final Dialect dialect = getFactory().getDialect();
	final RowSelection selection = queryParameters.getRowSelection();
	final boolean useLimit = LimitHelper.useLimit( limitHandler, selection );
	final boolean hasFirstRow = LimitHelper.hasFirstRow( selection );
	final boolean useLimitOffset = hasFirstRow && useLimit && limitHandler.supportsLimitOffset();
	final boolean callable = queryParameters.isCallable();
	final ScrollMode scrollMode = getScrollMode( scroll, hasFirstRow, useLimitOffset, queryParameters );

	PreparedStatement st = session.getJdbcCoordinator().getStatementPreparer().prepareQueryStatement(
			sql,
			callable,
			scrollMode
	);

	try {

		int col = 1;
		//TODO: can we limit stored procedures ?!
		col += limitHandler.bindLimitParametersAtStartOfQuery( selection, st, col );

		if ( callable ) {
			col = dialect.registerResultSetOutParameter( (CallableStatement) st, col );
		}

		col += bindParameterValues( st, queryParameters, col, session );

		col += limitHandler.bindLimitParametersAtEndOfQuery( selection, st, col );

		limitHandler.setMaxRows( selection, st );

		if ( selection != null ) {
			if ( selection.getTimeout() != null ) {
				st.setQueryTimeout( selection.getTimeout() );
			}
			if ( selection.getFetchSize() != null ) {
				st.setFetchSize( selection.getFetchSize() );
			}
		}

		// handle lock timeout...
		LockOptions lockOptions = queryParameters.getLockOptions();
		if ( lockOptions != null ) {
			if ( lockOptions.getTimeOut() != LockOptions.WAIT_FOREVER ) {
				if ( !dialect.supportsLockTimeouts() ) {
					if ( LOG.isDebugEnabled() ) {
						LOG.debugf(
								"Lock timeout [%s] requested but dialect reported to not support lock timeouts",
								lockOptions.getTimeOut()
						);
					}
				}
				else if ( dialect.isLockTimeoutParameterized() ) {
					st.setInt( col++, lockOptions.getTimeOut() );
				}
			}
		}

		if ( LOG.isTraceEnabled() ) {
			LOG.tracev( "Bound [{0}] parameters total", col );
		}
	}
	catch (SQLException | HibernateException e) {
		session.getJdbcCoordinator().getLogicalConnection().getResourceRegistry().release( st );
		session.getJdbcCoordinator().afterStatementExecution();
		throw e;
	}

	return st;
}
 
Example #30
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();

}