Example usage for org.springframework.transaction TransactionDefinition PROPAGATION_NOT_SUPPORTED

List of usage examples for org.springframework.transaction TransactionDefinition PROPAGATION_NOT_SUPPORTED

Introduction

In this page you can find the example usage for org.springframework.transaction TransactionDefinition PROPAGATION_NOT_SUPPORTED.

Prototype

int PROPAGATION_NOT_SUPPORTED

To view the source code for org.springframework.transaction TransactionDefinition PROPAGATION_NOT_SUPPORTED.

Click Source Link

Document

Do not support a current transaction; rather always execute non-transactionally.

Usage

From source file:com.alibaba.otter.node.etl.load.loader.db.interceptor.operation.AbstractOperationInterceptor.java

private void init(final JdbcTemplate jdbcTemplate, final String markTableName, final String markTableColumn) {
    int count = jdbcTemplate
            .queryForInt(MessageFormat.format(checkDataSql, markTableName, GLOBAL_THREAD_COUNT - 1));
    if (count != GLOBAL_THREAD_COUNT) {
        if (logger.isInfoEnabled()) {
            logger.info("Interceptor: init " + markTableName + "'s data.");
        }/* www .  j av a  2s.  co m*/
        TransactionTemplate transactionTemplate = new TransactionTemplate();
        transactionTemplate
                .setTransactionManager(new DataSourceTransactionManager(jdbcTemplate.getDataSource()));
        transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);// ??????
        transactionTemplate.execute(new TransactionCallback() {

            public Object doInTransaction(TransactionStatus status) {
                jdbcTemplate.execute(MessageFormat.format(deleteDataSql, markTableName));
                String batchSql = MessageFormat.format(updateSql,
                        new Object[] { markTableName, markTableColumn });
                jdbcTemplate.batchUpdate(batchSql, new BatchPreparedStatementSetter() {

                    public void setValues(PreparedStatement ps, int idx) throws SQLException {
                        ps.setInt(1, idx);
                        ps.setInt(2, 0);
                        // ps.setNull(3, Types.VARCHAR);
                    }

                    public int getBatchSize() {
                        return GLOBAL_THREAD_COUNT;
                    }
                });
                return null;
            }
        });

        if (logger.isInfoEnabled()) {
            logger.info("Interceptor: Init EROSA Client Data: " + updateSql);
        }
    }

}

From source file:com._4dconcept.springframework.data.marklogic.datasource.DatabaseConnectorJtaTransactionTest.java

private void doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(final boolean requiresNew,
        boolean notSupported) throws Exception {

    if (notSupported) {
        given(userTransaction.getStatus()).willReturn(Status.STATUS_ACTIVE, Status.STATUS_NO_TRANSACTION,
                Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
        given(transactionManager.suspend()).willReturn(transaction);
    } else {/*from ww  w.  j  a va2  s  .  c  o  m*/
        given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION,
                Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
    }

    final ContentSource contentSource = mock(ContentSource.class);
    final Session session1 = mock(Session.class);
    final Session session2 = mock(Session.class);
    given(contentSource.newSession()).willReturn(session1, session2);

    final JtaTransactionManager ptm = new JtaTransactionManager(userTransaction, transactionManager);
    TransactionTemplate tt = new TransactionTemplate(ptm);
    tt.setPropagationBehavior(notSupported ? TransactionDefinition.PROPAGATION_NOT_SUPPORTED
            : TransactionDefinition.PROPAGATION_SUPPORTS);

    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
            assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
            assertSame(session1, ContentSourceUtils.getSession(contentSource));
            assertSame(session1, ContentSourceUtils.getSession(contentSource));

            TransactionTemplate tt2 = new TransactionTemplate(ptm);
            tt2.setPropagationBehavior(requiresNew ? TransactionDefinition.PROPAGATION_REQUIRES_NEW
                    : TransactionDefinition.PROPAGATION_REQUIRED);
            tt2.execute(new TransactionCallbackWithoutResult() {
                @Override
                protected void doInTransactionWithoutResult(TransactionStatus status) {
                    assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
                    assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
                    assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
                    assertSame(session2, ContentSourceUtils.getSession(contentSource));
                    assertSame(session2, ContentSourceUtils.getSession(contentSource));
                }
            });

            assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
            assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
            assertSame(session1, ContentSourceUtils.getSession(contentSource));
        }
    });
    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
    verify(userTransaction).begin();
    verify(userTransaction).commit();
    if (notSupported) {
        verify(transactionManager).resume(transaction);
    }
    verify(session2).close();
    verify(session1).close();
}

From source file:org.springframework.test.context.transaction.TransactionalTestExecutionListener.java

/**
 * If the test method of the supplied {@linkplain TestContext test context}
 * is configured to run within a transaction, this method will run
 * {@link BeforeTransaction @BeforeTransaction} methods and start a new
 * transaction./*from   ww w  .  j ava  2  s  .co  m*/
 * <p>Note that if a {@code @BeforeTransaction} method fails, any remaining
 * {@code @BeforeTransaction} methods will not be invoked, and a transaction
 * will not be started.
 * @see org.springframework.transaction.annotation.Transactional
 * @see #getTransactionManager(TestContext, String)
 */
@Override
public void beforeTestMethod(final TestContext testContext) throws Exception {
    Method testMethod = testContext.getTestMethod();
    Class<?> testClass = testContext.getTestClass();
    Assert.notNull(testMethod, "The test method of the supplied TestContext must not be null");

    TransactionContext txContext = TransactionContextHolder.removeCurrentTransactionContext();
    Assert.state(txContext == null, "Cannot start a new transaction without ending the existing transaction.");

    PlatformTransactionManager tm = null;
    TransactionAttribute transactionAttribute = this.attributeSource.getTransactionAttribute(testMethod,
            testClass);

    if (transactionAttribute != null) {
        transactionAttribute = TestContextTransactionUtils.createDelegatingTransactionAttribute(testContext,
                transactionAttribute);

        if (logger.isDebugEnabled()) {
            logger.debug("Explicit transaction definition [" + transactionAttribute
                    + "] found for test context " + testContext);
        }

        if (transactionAttribute.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NOT_SUPPORTED) {
            return;
        }

        tm = getTransactionManager(testContext, transactionAttribute.getQualifier());
        Assert.state(tm != null, () -> String.format(
                "Failed to retrieve PlatformTransactionManager for @Transactional test for test context %s.",
                testContext));
    }

    if (tm != null) {
        txContext = new TransactionContext(testContext, tm, transactionAttribute, isRollback(testContext));
        runBeforeTransactionMethods(testContext);
        txContext.startTransaction();
        TransactionContextHolder.setCurrentTransactionContext(txContext);
    }
}

From source file:org.springframework.transaction.reactive.AbstractReactiveTransactionManager.java

/**
 * Create a ReactiveTransaction for an existing transaction.
 *///  w  ww  .ja  v a  2 s.  c om
private Mono<ReactiveTransaction> handleExistingTransaction(
        TransactionSynchronizationManager synchronizationManager, TransactionDefinition definition,
        Object transaction, boolean debugEnabled) throws TransactionException {

    if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NEVER) {
        return Mono.error(new IllegalTransactionStateException(
                "Existing transaction found for transaction marked with propagation 'never'"));
    }

    if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NOT_SUPPORTED) {
        if (debugEnabled) {
            logger.debug("Suspending current transaction");
        }
        Mono<SuspendedResourcesHolder> suspend = suspend(synchronizationManager, transaction);
        return suspend
                .map(suspendedResources -> prepareReactiveTransaction(synchronizationManager, definition, null,
                        false, debugEnabled, suspendedResources)) //
                .switchIfEmpty(Mono.fromSupplier(() -> prepareReactiveTransaction(synchronizationManager,
                        definition, null, false, debugEnabled, null)))
                .cast(ReactiveTransaction.class);
    }

    if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW) {
        if (debugEnabled) {
            logger.debug("Suspending current transaction, creating new transaction with name ["
                    + definition.getName() + "]");
        }
        Mono<SuspendedResourcesHolder> suspendedResources = suspend(synchronizationManager, transaction);
        return suspendedResources.flatMap(suspendedResourcesHolder -> {
            GenericReactiveTransaction status = newReactiveTransaction(synchronizationManager, definition,
                    transaction, true, debugEnabled, suspendedResourcesHolder);
            return doBegin(synchronizationManager, transaction, definition)
                    .doOnSuccess(ignore -> prepareSynchronization(synchronizationManager, status, definition))
                    .thenReturn(status).onErrorResume(ErrorPredicates.RUNTIME_OR_ERROR,
                            beginEx -> resumeAfterBeginException(synchronizationManager, transaction,
                                    suspendedResourcesHolder, beginEx).then(Mono.error(beginEx)));
        });
    }

    if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
        if (debugEnabled) {
            logger.debug("Creating nested transaction with name [" + definition.getName() + "]");
        }
        // Nested transaction through nested begin and commit/rollback calls.
        GenericReactiveTransaction status = newReactiveTransaction(synchronizationManager, definition,
                transaction, true, debugEnabled, null);
        return doBegin(synchronizationManager, transaction, definition)
                .doOnSuccess(ignore -> prepareSynchronization(synchronizationManager, status, definition))
                .thenReturn(status);
    }

    // Assumably PROPAGATION_SUPPORTS or PROPAGATION_REQUIRED.
    if (debugEnabled) {
        logger.debug("Participating in existing transaction");
    }
    return Mono.just(prepareReactiveTransaction(synchronizationManager, definition, transaction, false,
            debugEnabled, null));
}

From source file:org.springframework.transaction.support.AbstractPlatformTransactionManager.java

/**
 * Create a TransactionStatus for an existing transaction.
 *//*from   w w w .j  a v  a 2 s  . c  om*/
private TransactionStatus handleExistingTransaction(TransactionDefinition definition, Object transaction,
        boolean debugEnabled) throws TransactionException {

    if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NEVER) {
        throw new IllegalTransactionStateException(
                "Existing transaction found for transaction marked with propagation 'never'");
    }

    if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NOT_SUPPORTED) {
        if (debugEnabled) {
            logger.debug("Suspending current transaction");
        }
        Object suspendedResources = suspend(transaction);
        boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
        return prepareTransactionStatus(definition, null, false, newSynchronization, debugEnabled,
                suspendedResources);
    }

    if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW) {
        if (debugEnabled) {
            logger.debug("Suspending current transaction, creating new transaction with name ["
                    + definition.getName() + "]");
        }
        SuspendedResourcesHolder suspendedResources = suspend(transaction);
        try {
            boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
            DefaultTransactionStatus status = newTransactionStatus(definition, transaction, true,
                    newSynchronization, debugEnabled, suspendedResources);
            doBegin(transaction, definition);
            prepareSynchronization(status, definition);
            return status;
        } catch (RuntimeException | Error beginEx) {
            resumeAfterBeginException(transaction, suspendedResources, beginEx);
            throw beginEx;
        }
    }

    if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
        if (!isNestedTransactionAllowed()) {
            throw new NestedTransactionNotSupportedException(
                    "Transaction manager does not allow nested transactions by default - "
                            + "specify 'nestedTransactionAllowed' property with value 'true'");
        }
        if (debugEnabled) {
            logger.debug("Creating nested transaction with name [" + definition.getName() + "]");
        }
        if (useSavepointForNestedTransaction()) {
            // Create savepoint within existing Spring-managed transaction,
            // through the SavepointManager API implemented by TransactionStatus.
            // Usually uses JDBC 3.0 savepoints. Never activates Spring synchronization.
            DefaultTransactionStatus status = prepareTransactionStatus(definition, transaction, false, false,
                    debugEnabled, null);
            status.createAndHoldSavepoint();
            return status;
        } else {
            // Nested transaction through nested begin and commit/rollback calls.
            // Usually only for JTA: Spring synchronization might get activated here
            // in case of a pre-existing JTA transaction.
            boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
            DefaultTransactionStatus status = newTransactionStatus(definition, transaction, true,
                    newSynchronization, debugEnabled, null);
            doBegin(transaction, definition);
            prepareSynchronization(status, definition);
            return status;
        }
    }

    // Assumably PROPAGATION_SUPPORTS or PROPAGATION_REQUIRED.
    if (debugEnabled) {
        logger.debug("Participating in existing transaction");
    }
    if (isValidateExistingTransaction()) {
        if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
            Integer currentIsolationLevel = TransactionSynchronizationManager
                    .getCurrentTransactionIsolationLevel();
            if (currentIsolationLevel == null || currentIsolationLevel != definition.getIsolationLevel()) {
                Constants isoConstants = DefaultTransactionDefinition.constants;
                throw new IllegalTransactionStateException("Participating transaction with definition ["
                        + definition
                        + "] specifies isolation level which is incompatible with existing transaction: "
                        + (currentIsolationLevel != null
                                ? isoConstants.toCode(currentIsolationLevel,
                                        DefaultTransactionDefinition.PREFIX_ISOLATION)
                                : "(unknown)"));
            }
        }
        if (!definition.isReadOnly()) {
            if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
                throw new IllegalTransactionStateException("Participating transaction with definition ["
                        + definition + "] is not marked as read-only but existing transaction is");
            }
        }
    }
    boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
    return prepareTransactionStatus(definition, transaction, false, newSynchronization, debugEnabled, null);
}