Java Code Examples for org.hibernate.ScrollMode

The following examples show how to use org.hibernate.ScrollMode. 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
/**
 * <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 2
Source Project: lams   Source File: Loader.java    License: 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 3
Source Project: lams   Source File: SessionImpl.java    License: 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 4
Source Project: lams   Source File: StatelessSessionImpl.java    License: 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 5
/**
 * 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 6
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 7
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 8
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 9
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
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
@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 12
/**
 * 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 13
/**
 * 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 14
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 15
Source Project: lams   Source File: NativeQueryImpl.java    License: 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 16
Source Project: lams   Source File: AbstractProducedQuery.java    License: 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 17
Source Project: lams   Source File: AbstractProducedQuery.java    License: 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 18
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 19
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 20
public ScrollableResults scroll(ScrollMode scrollMode) {
	before();
	try {
		return session.scroll(this, scrollMode);
	}
	finally {
		after();
	}
}
 
Example 21
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 22
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
@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 24
@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 25
@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 26
SpringHibernateTransaction get(Session session, PlatformTransactionManager txManager,
TransactionStatus txStatus, boolean isScrollEnabled, ScrollMode scrollMode);
 
Example 27
Source Project: md_blockchain   Source File: SQLiteDialect.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public ScrollMode defaultScrollMode() {
    return ScrollMode.FORWARD_ONLY;
}
 
Example 28
Source Project: lams   Source File: CriteriaLoader.java    License: 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 29
Source Project: lams   Source File: Loader.java    License: 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
/**
 * 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(
		final String sql,
		final QueryParameters queryParameters,
		final LimitHandler limitHandler,
		final boolean scroll,
		final SharedSessionContractImplementor session) throws SQLException, HibernateException {
	final Dialect dialect = session.getJdbcServices().getJdbcEnvironment().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 );

	final 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...
		final 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 sqle ) {
		session.getJdbcCoordinator().getResourceRegistry().release( st );
		session.getJdbcCoordinator().afterStatementExecution();
		throw sqle;
	}
	catch ( HibernateException he ) {
		session.getJdbcCoordinator().getResourceRegistry().release( st );
		session.getJdbcCoordinator().afterStatementExecution();
		throw he;
	}

	return st;
}