Search in sources :

Example 6 with CannotCreateTransactionException

use of org.springframework.transaction.CannotCreateTransactionException in project spring-framework by spring-projects.

the class DataSourceTransactionManager method doBegin.

@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
    DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
    Connection con = null;
    try {
        if (!txObject.hasConnectionHolder() || txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
            Connection newCon = obtainDataSource().getConnection();
            if (logger.isDebugEnabled()) {
                logger.debug("Acquired Connection [" + newCon + "] for JDBC transaction");
            }
            txObject.setConnectionHolder(new ConnectionHolder(newCon), true);
        }
        txObject.getConnectionHolder().setSynchronizedWithTransaction(true);
        con = txObject.getConnectionHolder().getConnection();
        Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
        txObject.setPreviousIsolationLevel(previousIsolationLevel);
        txObject.setReadOnly(definition.isReadOnly());
        // configured the connection pool to set it already).
        if (con.getAutoCommit()) {
            txObject.setMustRestoreAutoCommit(true);
            if (logger.isDebugEnabled()) {
                logger.debug("Switching JDBC Connection [" + con + "] to manual commit");
            }
            con.setAutoCommit(false);
        }
        prepareTransactionalConnection(con, definition);
        txObject.getConnectionHolder().setTransactionActive(true);
        int timeout = determineTimeout(definition);
        if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
            txObject.getConnectionHolder().setTimeoutInSeconds(timeout);
        }
        // Bind the connection holder to the thread.
        if (txObject.isNewConnectionHolder()) {
            TransactionSynchronizationManager.bindResource(obtainDataSource(), txObject.getConnectionHolder());
        }
    } catch (Throwable ex) {
        if (txObject.isNewConnectionHolder()) {
            DataSourceUtils.releaseConnection(con, obtainDataSource());
            txObject.setConnectionHolder(null, false);
        }
        throw new CannotCreateTransactionException("Could not open JDBC Connection for transaction", ex);
    }
}
Also used : CannotCreateTransactionException(org.springframework.transaction.CannotCreateTransactionException) Connection(java.sql.Connection)

Example 7 with CannotCreateTransactionException

use of org.springframework.transaction.CannotCreateTransactionException in project spring-framework by spring-projects.

the class CciLocalTransactionManager method doBegin.

@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
    CciLocalTransactionObject txObject = (CciLocalTransactionObject) transaction;
    Connection con = null;
    try {
        con = getConnectionFactory().getConnection();
        if (logger.isDebugEnabled()) {
            logger.debug("Acquired Connection [" + con + "] for local CCI transaction");
        }
        txObject.setConnectionHolder(new ConnectionHolder(con));
        txObject.getConnectionHolder().setSynchronizedWithTransaction(true);
        con.getLocalTransaction().begin();
        int timeout = determineTimeout(definition);
        if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
            txObject.getConnectionHolder().setTimeoutInSeconds(timeout);
        }
        TransactionSynchronizationManager.bindResource(getConnectionFactory(), txObject.getConnectionHolder());
    } catch (NotSupportedException ex) {
        ConnectionFactoryUtils.releaseConnection(con, getConnectionFactory());
        throw new CannotCreateTransactionException("CCI Connection does not support local transactions", ex);
    } catch (LocalTransactionException ex) {
        ConnectionFactoryUtils.releaseConnection(con, getConnectionFactory());
        throw new CannotCreateTransactionException("Could not begin local CCI transaction", ex);
    } catch (Throwable ex) {
        ConnectionFactoryUtils.releaseConnection(con, getConnectionFactory());
        throw new TransactionSystemException("Unexpected failure on begin of CCI local transaction", ex);
    }
}
Also used : LocalTransactionException(javax.resource.spi.LocalTransactionException) CannotCreateTransactionException(org.springframework.transaction.CannotCreateTransactionException) Connection(javax.resource.cci.Connection) TransactionSystemException(org.springframework.transaction.TransactionSystemException) NotSupportedException(javax.resource.NotSupportedException)

Example 8 with CannotCreateTransactionException

use of org.springframework.transaction.CannotCreateTransactionException in project spring-framework by spring-projects.

the class JpaTransactionManager method doBegin.

@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
    JpaTransactionObject txObject = (JpaTransactionObject) transaction;
    if (txObject.hasConnectionHolder() && !txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
        throw new IllegalTransactionStateException("Pre-bound JDBC Connection found! JpaTransactionManager does not support " + "running within DataSourceTransactionManager if told to manage the DataSource itself. " + "It is recommended to use a single JpaTransactionManager for all transactions " + "on a single DataSource, no matter whether JPA or JDBC access.");
    }
    try {
        if (txObject.getEntityManagerHolder() == null || txObject.getEntityManagerHolder().isSynchronizedWithTransaction()) {
            EntityManager newEm = createEntityManagerForTransaction();
            if (logger.isDebugEnabled()) {
                logger.debug("Opened new EntityManager [" + newEm + "] for JPA transaction");
            }
            txObject.setEntityManagerHolder(new EntityManagerHolder(newEm), true);
        }
        EntityManager em = txObject.getEntityManagerHolder().getEntityManager();
        // Delegate to JpaDialect for actual transaction begin.
        final int timeoutToUse = determineTimeout(definition);
        Object transactionData = getJpaDialect().beginTransaction(em, new DelegatingTransactionDefinition(definition) {

            @Override
            public int getTimeout() {
                return timeoutToUse;
            }
        });
        txObject.setTransactionData(transactionData);
        // Register transaction timeout.
        if (timeoutToUse != TransactionDefinition.TIMEOUT_DEFAULT) {
            txObject.getEntityManagerHolder().setTimeoutInSeconds(timeoutToUse);
        }
        // Register the JPA EntityManager's JDBC Connection for the DataSource, if set.
        if (getDataSource() != null) {
            ConnectionHandle conHandle = getJpaDialect().getJdbcConnection(em, definition.isReadOnly());
            if (conHandle != null) {
                ConnectionHolder conHolder = new ConnectionHolder(conHandle);
                if (timeoutToUse != TransactionDefinition.TIMEOUT_DEFAULT) {
                    conHolder.setTimeoutInSeconds(timeoutToUse);
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Exposing JPA transaction as JDBC transaction [" + conHolder.getConnectionHandle() + "]");
                }
                TransactionSynchronizationManager.bindResource(getDataSource(), conHolder);
                txObject.setConnectionHolder(conHolder);
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("Not exposing JPA transaction [" + em + "] as JDBC transaction because " + "JpaDialect [" + getJpaDialect() + "] does not support JDBC Connection retrieval");
                }
            }
        }
        // Bind the entity manager holder to the thread.
        if (txObject.isNewEntityManagerHolder()) {
            TransactionSynchronizationManager.bindResource(getEntityManagerFactory(), txObject.getEntityManagerHolder());
        }
        txObject.getEntityManagerHolder().setSynchronizedWithTransaction(true);
    } catch (TransactionException ex) {
        closeEntityManagerAfterFailedBegin(txObject);
        throw ex;
    } catch (Throwable ex) {
        closeEntityManagerAfterFailedBegin(txObject);
        throw new CannotCreateTransactionException("Could not open JPA EntityManager for transaction", ex);
    }
}
Also used : DelegatingTransactionDefinition(org.springframework.transaction.support.DelegatingTransactionDefinition) ConnectionHandle(org.springframework.jdbc.datasource.ConnectionHandle) CannotCreateTransactionException(org.springframework.transaction.CannotCreateTransactionException) IllegalTransactionStateException(org.springframework.transaction.IllegalTransactionStateException) ConnectionHolder(org.springframework.jdbc.datasource.ConnectionHolder) EntityManager(javax.persistence.EntityManager) CannotCreateTransactionException(org.springframework.transaction.CannotCreateTransactionException) TransactionException(org.springframework.transaction.TransactionException)

Example 9 with CannotCreateTransactionException

use of org.springframework.transaction.CannotCreateTransactionException in project spring-data-commons by spring-projects.

the class ChainedTransactionManager method getTransaction.

/*
	 * (non-Javadoc)
	 * @see org.springframework.transaction.PlatformTransactionManager#getTransaction(org.springframework.transaction.TransactionDefinition)
	 */
public MultiTransactionStatus getTransaction(@Nullable TransactionDefinition definition) throws TransactionException {
    MultiTransactionStatus mts = new MultiTransactionStatus(transactionManagers.get(0));
    if (definition == null) {
        return mts;
    }
    if (!synchronizationManager.isSynchronizationActive()) {
        synchronizationManager.initSynchronization();
        mts.setNewSynchonization();
    }
    try {
        for (PlatformTransactionManager transactionManager : transactionManagers) {
            mts.registerTransactionManager(definition, transactionManager);
        }
    } catch (Exception ex) {
        Map<PlatformTransactionManager, TransactionStatus> transactionStatuses = mts.getTransactionStatuses();
        for (PlatformTransactionManager transactionManager : transactionManagers) {
            try {
                if (transactionStatuses.get(transactionManager) != null) {
                    transactionManager.rollback(transactionStatuses.get(transactionManager));
                }
            } catch (Exception ex2) {
                LOGGER.warn("Rollback exception (" + transactionManager + ") " + ex2.getMessage(), ex2);
            }
        }
        if (mts.isNewSynchonization()) {
            synchronizationManager.clearSynchronization();
        }
        throw new CannotCreateTransactionException(ex.getMessage(), ex);
    }
    return mts;
}
Also used : CannotCreateTransactionException(org.springframework.transaction.CannotCreateTransactionException) Map(java.util.Map) PlatformTransactionManager(org.springframework.transaction.PlatformTransactionManager) UnexpectedRollbackException(org.springframework.transaction.UnexpectedRollbackException) TransactionException(org.springframework.transaction.TransactionException) CannotCreateTransactionException(org.springframework.transaction.CannotCreateTransactionException) HeuristicCompletionException(org.springframework.transaction.HeuristicCompletionException)

Example 10 with CannotCreateTransactionException

use of org.springframework.transaction.CannotCreateTransactionException in project spring-framework by spring-projects.

the class AbstractReactiveTransactionAspectTests method cannotCreateTransaction.

/**
 * Simulate a transaction infrastructure failure.
 * Shouldn't invoke target method.
 */
@Test
public void cannotCreateTransaction() throws Exception {
    TransactionAttribute txatt = new DefaultTransactionAttribute();
    Method m = getNameMethod;
    MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
    tas.register(m, txatt);
    ReactiveTransactionManager rtm = mock(ReactiveTransactionManager.class);
    // Expect a transaction
    CannotCreateTransactionException ex = new CannotCreateTransactionException("foobar", null);
    given(rtm.getReactiveTransaction(txatt)).willThrow(ex);
    DefaultTestBean tb = new DefaultTestBean() {

        @Override
        public Mono<String> getName() {
            throw new UnsupportedOperationException("Shouldn't have invoked target method when couldn't create transaction for transactional method");
        }
    };
    TestBean itb = (TestBean) advised(tb, rtm, tas);
    itb.getName().as(StepVerifier::create).expectError(CannotCreateTransactionException.class).verify();
}
Also used : CannotCreateTransactionException(org.springframework.transaction.CannotCreateTransactionException) ReactiveTransactionManager(org.springframework.transaction.ReactiveTransactionManager) Method(java.lang.reflect.Method) StepVerifier(reactor.test.StepVerifier) Test(org.junit.jupiter.api.Test)

Aggregations

CannotCreateTransactionException (org.springframework.transaction.CannotCreateTransactionException)11 TransactionException (org.springframework.transaction.TransactionException)4 InvalidIsolationLevelException (org.springframework.transaction.InvalidIsolationLevelException)3 PlatformTransactionManager (org.springframework.transaction.PlatformTransactionManager)3 Method (java.lang.reflect.Method)2 Connection (java.sql.Connection)2 Map (java.util.Map)2 Test (org.junit.jupiter.api.Test)2 ConnectionHolder (org.springframework.jdbc.datasource.ConnectionHolder)2 HeuristicCompletionException (org.springframework.transaction.HeuristicCompletionException)2 IllegalTransactionStateException (org.springframework.transaction.IllegalTransactionStateException)2 TransactionSystemException (org.springframework.transaction.TransactionSystemException)2 UnexpectedRollbackException (org.springframework.transaction.UnexpectedRollbackException)2 TransactionContext (com.hazelcast.transaction.TransactionContext)1 Connection (jakarta.jms.Connection)1 ConnectionFactory (jakarta.jms.ConnectionFactory)1 Session (jakarta.jms.Session)1 EntityManager (javax.persistence.EntityManager)1 NotSupportedException (javax.resource.NotSupportedException)1 Connection (javax.resource.cci.Connection)1