Search in sources :

Example 6 with LockOptions

use of org.hibernate.LockOptions in project hibernate-orm by hibernate.

the class Loader method shouldUseFollowOnLocking.

protected boolean shouldUseFollowOnLocking(QueryParameters parameters, Dialect dialect, List<AfterLoadAction> afterLoadActions) {
    if ((parameters.getLockOptions().getFollowOnLocking() == null && dialect.useFollowOnLocking(parameters)) || (parameters.getLockOptions().getFollowOnLocking() != null && parameters.getLockOptions().getFollowOnLocking())) {
        // currently only one lock mode is allowed in follow-on locking
        final LockMode lockMode = determineFollowOnLockMode(parameters.getLockOptions());
        final LockOptions lockOptions = new LockOptions(lockMode);
        if (lockOptions.getLockMode() != LockMode.UPGRADE_SKIPLOCKED) {
            if (lockOptions.getLockMode() != LockMode.NONE) {
                LOG.usingFollowOnLocking();
            }
            lockOptions.setTimeOut(parameters.getLockOptions().getTimeOut());
            lockOptions.setScope(parameters.getLockOptions().getScope());
            afterLoadActions.add(new AfterLoadAction() {

                @Override
                public void afterLoad(SharedSessionContractImplementor session, Object entity, Loadable persister) {
                    ((Session) session).buildLockRequest(lockOptions).lock(persister.getEntityName(), entity);
                }
            });
            parameters.setLockOptions(new LockOptions());
            return true;
        }
    }
    return false;
}
Also used : UniqueKeyLoadable(org.hibernate.persister.entity.UniqueKeyLoadable) Loadable(org.hibernate.persister.entity.Loadable) LockOptions(org.hibernate.LockOptions) AfterLoadAction(org.hibernate.loader.spi.AfterLoadAction) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) LockMode(org.hibernate.LockMode) Session(org.hibernate.Session)

Example 7 with LockOptions

use of org.hibernate.LockOptions in project hibernate-orm by hibernate.

the class DynamicBatchingEntityLoaderBuilder method performOrderedMultiLoad.

@SuppressWarnings("unchecked")
private List performOrderedMultiLoad(OuterJoinLoadable persister, Serializable[] ids, SharedSessionContractImplementor session, MultiLoadOptions loadOptions) {
    assert loadOptions.isOrderReturnEnabled();
    final List result = CollectionHelper.arrayList(ids.length);
    final LockOptions lockOptions = (loadOptions.getLockOptions() == null) ? new LockOptions(LockMode.NONE) : loadOptions.getLockOptions();
    final int maxBatchSize;
    if (loadOptions.getBatchSize() != null && loadOptions.getBatchSize() > 0) {
        maxBatchSize = loadOptions.getBatchSize();
    } else {
        maxBatchSize = session.getJdbcServices().getJdbcEnvironment().getDialect().getDefaultBatchLoadSizingStrategy().determineOptimalBatchLoadSize(persister.getIdentifierType().getColumnSpan(session.getFactory()), ids.length);
    }
    final List<Serializable> idsInBatch = new ArrayList<>();
    final List<Integer> elementPositionsLoadedByBatch = new ArrayList<>();
    for (int i = 0; i < ids.length; i++) {
        final Serializable id = ids[i];
        final EntityKey entityKey = new EntityKey(id, persister);
        if (loadOptions.isSessionCheckingEnabled()) {
            // look for it in the Session first
            final Object managedEntity = session.getPersistenceContext().getEntity(entityKey);
            if (managedEntity != null) {
                if (!loadOptions.isReturnOfDeletedEntitiesEnabled()) {
                    final EntityEntry entry = session.getPersistenceContext().getEntry(managedEntity);
                    if (entry.getStatus() == Status.DELETED || entry.getStatus() == Status.GONE) {
                        // put a null in the result
                        result.add(i, null);
                        continue;
                    }
                }
                // if we did not hit the continue above, there is already an
                // entry in the PC for that entity, so use it...
                result.add(i, managedEntity);
                continue;
            }
        }
        // if we did not hit any of the continues above, then we need to batch
        // load the entity state.
        idsInBatch.add(ids[i]);
        if (idsInBatch.size() >= maxBatchSize) {
            performOrderedBatchLoad(idsInBatch, lockOptions, persister, session);
        }
        // Save the EntityKey instance for use later!
        result.add(i, entityKey);
        elementPositionsLoadedByBatch.add(i);
    }
    if (!idsInBatch.isEmpty()) {
        performOrderedBatchLoad(idsInBatch, lockOptions, persister, session);
    }
    for (Integer position : elementPositionsLoadedByBatch) {
        // the element value at this position in the result List should be
        // the EntityKey for that entity; reuse it!
        final EntityKey entityKey = (EntityKey) result.get(position);
        Object entity = session.getPersistenceContext().getEntity(entityKey);
        if (entity != null && !loadOptions.isReturnOfDeletedEntitiesEnabled()) {
            // make sure it is not DELETED
            final EntityEntry entry = session.getPersistenceContext().getEntry(entity);
            if (entry.getStatus() == Status.DELETED || entry.getStatus() == Status.GONE) {
                // the entity is locally deleted, and the options ask that we not return such entities...
                entity = null;
            }
        }
        result.set(position, entity);
    }
    return result;
}
Also used : EntityKey(org.hibernate.engine.spi.EntityKey) Serializable(java.io.Serializable) EntityEntry(org.hibernate.engine.spi.EntityEntry) LockOptions(org.hibernate.LockOptions) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List)

Example 8 with LockOptions

use of org.hibernate.LockOptions in project hibernate-orm by hibernate.

the class Loader method prepareQueryStatement.

/**
	 * 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;
}
Also used : ScrollMode(org.hibernate.ScrollMode) LockOptions(org.hibernate.LockOptions) SQLException(java.sql.SQLException) HibernateException(org.hibernate.HibernateException) CallableStatement(java.sql.CallableStatement) Dialect(org.hibernate.dialect.Dialect) PreparedStatement(java.sql.PreparedStatement) RowSelection(org.hibernate.engine.spi.RowSelection)

Example 9 with LockOptions

use of org.hibernate.LockOptions in project hibernate-orm by hibernate.

the class SQLServer2005DialectTestCase method testAppendLockHintUpgradeNoWaitNoTimeout.

@Test
@TestForIssue(jiraKey = "HHH-9635")
public void testAppendLockHintUpgradeNoWaitNoTimeout() {
    final String expectedLockHint = "tab1 with (updlock, rowlock, nowait)";
    LockOptions lockOptions = new LockOptions(LockMode.UPGRADE_NOWAIT);
    lockOptions.setTimeOut(LockOptions.NO_WAIT);
    String lockHint = dialect.appendLockHint(lockOptions, "tab1");
    assertEquals(expectedLockHint, lockHint);
}
Also used : LockOptions(org.hibernate.LockOptions) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Example 10 with LockOptions

use of org.hibernate.LockOptions in project hibernate-orm by hibernate.

the class SQLServer2005DialectTestCase method testAppendLockHintWrite.

@Test
@TestForIssue(jiraKey = "HHH-9635")
public void testAppendLockHintWrite() {
    final String expectedLockHint = "tab1 with (updlock, rowlock)";
    LockOptions lockOptions = new LockOptions(LockMode.WRITE);
    String lockHint = dialect.appendLockHint(lockOptions, "tab1");
    assertEquals(expectedLockHint, lockHint);
}
Also used : LockOptions(org.hibernate.LockOptions) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Aggregations

LockOptions (org.hibernate.LockOptions)64 Test (org.junit.Test)43 Session (org.hibernate.Session)23 TestForIssue (org.hibernate.testing.TestForIssue)14 PersistenceException (javax.persistence.PersistenceException)5 SQLGrammarException (org.hibernate.exception.SQLGrammarException)5 LockMode (org.hibernate.LockMode)4 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 RowSelection (org.hibernate.engine.spi.RowSelection)3 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)3 SharedSessionContractImplementor (org.hibernate.engine.spi.SharedSessionContractImplementor)3 AfterLoadAction (org.hibernate.loader.spi.AfterLoadAction)3 Loadable (org.hibernate.persister.entity.Loadable)3 RequiresDialect (org.hibernate.testing.RequiresDialect)3 Serializable (java.io.Serializable)2 CallableStatement (java.sql.CallableStatement)2 PreparedStatement (java.sql.PreparedStatement)2 SQLException (java.sql.SQLException)2