Search in sources :

Example 56 with TransactionStatus

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

the class JpaTransactionManagerTests method testTransactionWithRequiresNewInAfterCompletion.

@Test
public void testTransactionWithRequiresNewInAfterCompletion() {
    tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    EntityManager manager2 = mock(EntityManager.class);
    EntityTransaction tx2 = mock(EntityTransaction.class);
    given(manager.getTransaction()).willReturn(tx);
    given(factory.createEntityManager()).willReturn(manager, manager2);
    given(manager2.getTransaction()).willReturn(tx2);
    given(manager2.isOpen()).willReturn(true);
    assertTrue(!TransactionSynchronizationManager.hasResource(factory));
    assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
    tt.execute(new TransactionCallback() {

        @Override
        public Object doInTransaction(TransactionStatus status) {
            EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {

                @Override
                public void afterCompletion(int status) {
                    tt.execute(new TransactionCallback() {

                        @Override
                        public Object doInTransaction(TransactionStatus status) {
                            EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
                            return null;
                        }
                    });
                }
            });
            return null;
        }
    });
    assertTrue(!TransactionSynchronizationManager.hasResource(factory));
    assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
    verify(tx).commit();
    verify(tx2).begin();
    verify(tx2).commit();
    verify(manager).flush();
    verify(manager).close();
    verify(manager2).flush();
    verify(manager2).close();
}
Also used : EntityTransaction(javax.persistence.EntityTransaction) EntityManager(javax.persistence.EntityManager) TransactionCallback(org.springframework.transaction.support.TransactionCallback) TransactionStatus(org.springframework.transaction.TransactionStatus) TransactionSynchronizationAdapter(org.springframework.transaction.support.TransactionSynchronizationAdapter) Test(org.junit.Test)

Example 57 with TransactionStatus

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

the class JpaTransactionManagerTests method testTransactionCommitWithPropagationSupports.

@Test
public void testTransactionCommitWithPropagationSupports() {
    given(manager.isOpen()).willReturn(true);
    final List<String> l = new ArrayList<>();
    l.add("test");
    tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
    assertTrue(!TransactionSynchronizationManager.hasResource(factory));
    assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
    Object result = tt.execute(new TransactionCallback() {

        @Override
        public Object doInTransaction(TransactionStatus status) {
            assertTrue(!TransactionSynchronizationManager.hasResource(factory));
            assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
            assertTrue(!status.isNewTransaction());
            EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
            return l;
        }
    });
    assertSame(l, result);
    assertTrue(!TransactionSynchronizationManager.hasResource(factory));
    assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
    verify(manager).flush();
    verify(manager).close();
}
Also used : TransactionCallback(org.springframework.transaction.support.TransactionCallback) ArrayList(java.util.ArrayList) TransactionStatus(org.springframework.transaction.TransactionStatus) Test(org.junit.Test)

Example 58 with TransactionStatus

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

the class JpaTransactionManagerTests method testTransactionRollbackOnly.

@Test
public void testTransactionRollbackOnly() {
    given(manager.getTransaction()).willReturn(tx);
    given(tx.isActive()).willReturn(true);
    final List<String> l = new ArrayList<>();
    l.add("test");
    assertTrue(!TransactionSynchronizationManager.hasResource(factory));
    assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
    tt.execute(new TransactionCallback() {

        @Override
        public Object doInTransaction(TransactionStatus status) {
            assertTrue(TransactionSynchronizationManager.hasResource(factory));
            EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
            status.setRollbackOnly();
            return l;
        }
    });
    assertTrue(!TransactionSynchronizationManager.hasResource(factory));
    assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
    verify(manager).flush();
    verify(tx).rollback();
    verify(manager).close();
}
Also used : TransactionCallback(org.springframework.transaction.support.TransactionCallback) ArrayList(java.util.ArrayList) TransactionStatus(org.springframework.transaction.TransactionStatus) Test(org.junit.Test)

Example 59 with TransactionStatus

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

the class TransactionAspectSupport method invokeWithinTransaction.

/**
	 * General delegate for around-advice-based subclasses, delegating to several other template
	 * methods on this class. Able to handle {@link CallbackPreferringPlatformTransactionManager}
	 * as well as regular {@link PlatformTransactionManager} implementations.
	 * @param method the Method being invoked
	 * @param targetClass the target class that we're invoking the method on
	 * @param invocation the callback to use for proceeding with the target invocation
	 * @return the return value of the method, if any
	 * @throws Throwable propagated from the target invocation
	 */
protected Object invokeWithinTransaction(Method method, Class<?> targetClass, final InvocationCallback invocation) throws Throwable {
    // If the transaction attribute is null, the method is non-transactional.
    final TransactionAttribute txAttr = getTransactionAttributeSource().getTransactionAttribute(method, targetClass);
    final PlatformTransactionManager tm = determineTransactionManager(txAttr);
    final String joinpointIdentification = methodIdentification(method, targetClass, txAttr);
    if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) {
        // Standard transaction demarcation with getTransaction and commit/rollback calls.
        TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification);
        Object retVal = null;
        try {
            // This is an around advice: Invoke the next interceptor in the chain.
            // This will normally result in a target object being invoked.
            retVal = invocation.proceedWithInvocation();
        } catch (Throwable ex) {
            // target invocation exception
            completeTransactionAfterThrowing(txInfo, ex);
            throw ex;
        } finally {
            cleanupTransactionInfo(txInfo);
        }
        commitTransactionAfterReturning(txInfo);
        return retVal;
    } else {
        // It's a CallbackPreferringPlatformTransactionManager: pass a TransactionCallback in.
        try {
            Object result = ((CallbackPreferringPlatformTransactionManager) tm).execute(txAttr, new TransactionCallback<Object>() {

                @Override
                public Object doInTransaction(TransactionStatus status) {
                    TransactionInfo txInfo = prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);
                    try {
                        return invocation.proceedWithInvocation();
                    } catch (Throwable ex) {
                        if (txAttr.rollbackOn(ex)) {
                            // A RuntimeException: will lead to a rollback.
                            if (ex instanceof RuntimeException) {
                                throw (RuntimeException) ex;
                            } else {
                                throw new ThrowableHolderException(ex);
                            }
                        } else {
                            // A normal return value: will lead to a commit.
                            return new ThrowableHolder(ex);
                        }
                    } finally {
                        cleanupTransactionInfo(txInfo);
                    }
                }
            });
            // Check result: It might indicate a Throwable to rethrow.
            if (result instanceof ThrowableHolder) {
                throw ((ThrowableHolder) result).getThrowable();
            } else {
                return result;
            }
        } catch (ThrowableHolderException ex) {
            throw ex.getCause();
        }
    }
}
Also used : TransactionStatus(org.springframework.transaction.TransactionStatus) CallbackPreferringPlatformTransactionManager(org.springframework.transaction.support.CallbackPreferringPlatformTransactionManager) PlatformTransactionManager(org.springframework.transaction.PlatformTransactionManager) CallbackPreferringPlatformTransactionManager(org.springframework.transaction.support.CallbackPreferringPlatformTransactionManager)

Example 60 with TransactionStatus

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

the class CciLocalTransactionTests method testLocalTransactionCommit.

/**
	 * Test if a transaction ( begin / commit ) is executed on the
	 * LocalTransaction when CciLocalTransactionManager is specified as
	 * transaction manager.
	 */
@Test
public void testLocalTransactionCommit() throws ResourceException {
    final ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
    Connection connection = mock(Connection.class);
    Interaction interaction = mock(Interaction.class);
    LocalTransaction localTransaction = mock(LocalTransaction.class);
    final Record record = mock(Record.class);
    final InteractionSpec interactionSpec = mock(InteractionSpec.class);
    given(connectionFactory.getConnection()).willReturn(connection);
    given(connection.getLocalTransaction()).willReturn(localTransaction);
    given(connection.createInteraction()).willReturn(interaction);
    given(interaction.execute(interactionSpec, record, record)).willReturn(true);
    given(connection.getLocalTransaction()).willReturn(localTransaction);
    CciLocalTransactionManager tm = new CciLocalTransactionManager();
    tm.setConnectionFactory(connectionFactory);
    TransactionTemplate tt = new TransactionTemplate(tm);
    tt.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(connectionFactory));
            CciTemplate ct = new CciTemplate(connectionFactory);
            ct.execute(interactionSpec, record, record);
        }
    });
    verify(localTransaction).begin();
    verify(interaction).close();
    verify(localTransaction).commit();
    verify(connection).close();
}
Also used : ConnectionFactory(javax.resource.cci.ConnectionFactory) LocalTransaction(javax.resource.cci.LocalTransaction) Interaction(javax.resource.cci.Interaction) InteractionSpec(javax.resource.cci.InteractionSpec) Connection(javax.resource.cci.Connection) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) TransactionStatus(org.springframework.transaction.TransactionStatus) Record(javax.resource.cci.Record) CciLocalTransactionManager(org.springframework.jca.cci.connection.CciLocalTransactionManager) CciTemplate(org.springframework.jca.cci.core.CciTemplate) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult) Test(org.junit.Test)

Aggregations

TransactionStatus (org.springframework.transaction.TransactionStatus)359 Test (org.junit.Test)186 TransactionCallbackWithoutResult (org.springframework.transaction.support.TransactionCallbackWithoutResult)154 TransactionCallback (org.springframework.transaction.support.TransactionCallback)91 TransactionTemplate (org.springframework.transaction.support.TransactionTemplate)72 DefaultTransactionDefinition (org.springframework.transaction.support.DefaultTransactionDefinition)32 List (java.util.List)28 ArrayList (java.util.ArrayList)27 SQLException (java.sql.SQLException)25 Connection (java.sql.Connection)21 Date (java.util.Date)18 PreparedStatement (java.sql.PreparedStatement)17 TransactionSynchronizationAdapter (org.springframework.transaction.support.TransactionSynchronizationAdapter)15 OnmsNode (org.opennms.netmgt.model.OnmsNode)14 ManagerException (com.alibaba.otter.manager.biz.common.exceptions.ManagerException)13 RepeatConfigureException (com.alibaba.otter.manager.biz.common.exceptions.RepeatConfigureException)13 UncategorizedSQLException (org.springframework.jdbc.UncategorizedSQLException)12 PlatformTransactionManager (org.springframework.transaction.PlatformTransactionManager)12 EntityManager (javax.persistence.EntityManager)11 DataSource (javax.sql.DataSource)11