Search in sources :

Example 6 with PlatformTransactionManager

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

the class TransactionalTestExecutionListener method beforeTestMethod.

/**
	 * 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.
	 * <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 {
    final Method testMethod = testContext.getTestMethod();
    final 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);
    }
}
Also used : TransactionAttribute(org.springframework.transaction.interceptor.TransactionAttribute) Method(java.lang.reflect.Method) PlatformTransactionManager(org.springframework.transaction.PlatformTransactionManager)

Example 7 with PlatformTransactionManager

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

the class TransactionAspectSupport method determineQualifiedTransactionManager.

private PlatformTransactionManager determineQualifiedTransactionManager(String qualifier) {
    PlatformTransactionManager txManager = this.transactionManagerCache.get(qualifier);
    if (txManager == null) {
        txManager = BeanFactoryAnnotationUtils.qualifiedBeanOfType(this.beanFactory, PlatformTransactionManager.class, qualifier);
        this.transactionManagerCache.putIfAbsent(qualifier, txManager);
    }
    return txManager;
}
Also used : CallbackPreferringPlatformTransactionManager(org.springframework.transaction.support.CallbackPreferringPlatformTransactionManager) PlatformTransactionManager(org.springframework.transaction.PlatformTransactionManager)

Example 8 with PlatformTransactionManager

use of org.springframework.transaction.PlatformTransactionManager 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 9 with PlatformTransactionManager

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

the class TransactionInterceptorTests method determineTransactionManagerDefaultSeveralTimes.

@Test
public void determineTransactionManagerDefaultSeveralTimes() {
    BeanFactory beanFactory = mock(BeanFactory.class);
    TransactionInterceptor ti = simpleTransactionInterceptor(beanFactory);
    PlatformTransactionManager txManager = mock(PlatformTransactionManager.class);
    given(beanFactory.getBean(PlatformTransactionManager.class)).willReturn(txManager);
    DefaultTransactionAttribute attribute = new DefaultTransactionAttribute();
    PlatformTransactionManager actual = ti.determineTransactionManager(attribute);
    assertSame(txManager, actual);
    // Call again, should be cached
    PlatformTransactionManager actual2 = ti.determineTransactionManager(attribute);
    assertSame(txManager, actual2);
    verify(beanFactory, times(1)).getBean(PlatformTransactionManager.class);
}
Also used : BeanFactory(org.springframework.beans.factory.BeanFactory) PlatformTransactionManager(org.springframework.transaction.PlatformTransactionManager) Test(org.junit.Test)

Example 10 with PlatformTransactionManager

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

the class TransactionInterceptorTests method serializableWithAttributeProperties.

/**
	 * A TransactionInterceptor should be serializable if its
	 * PlatformTransactionManager is.
	 */
@Test
public void serializableWithAttributeProperties() throws Exception {
    TransactionInterceptor ti = new TransactionInterceptor();
    Properties props = new Properties();
    props.setProperty("methodName", "PROPAGATION_REQUIRED");
    ti.setTransactionAttributes(props);
    PlatformTransactionManager ptm = new SerializableTransactionManager();
    ti.setTransactionManager(ptm);
    ti = (TransactionInterceptor) SerializationTestUtils.serializeAndDeserialize(ti);
    // Check that logger survived deserialization
    assertNotNull(ti.logger);
    assertTrue(ti.getTransactionManager() instanceof SerializableTransactionManager);
    assertNotNull(ti.getTransactionAttributeSource());
}
Also used : Properties(java.util.Properties) PlatformTransactionManager(org.springframework.transaction.PlatformTransactionManager) Test(org.junit.Test)

Aggregations

PlatformTransactionManager (org.springframework.transaction.PlatformTransactionManager)52 Test (org.junit.Test)32 TransactionStatus (org.springframework.transaction.TransactionStatus)13 ITestBean (org.springframework.tests.sample.beans.ITestBean)10 TestBean (org.springframework.tests.sample.beans.TestBean)10 BeanFactory (org.springframework.beans.factory.BeanFactory)7 Method (java.lang.reflect.Method)6 TransactionTemplate (org.springframework.transaction.support.TransactionTemplate)6 TestPlatformTransactionManager (org.grails.transaction.ChainedTransactionManagerTests.TestPlatformTransactionManager)5 IpInterfaceDao (org.opennms.netmgt.dao.api.IpInterfaceDao)5 OnmsIpInterface (org.opennms.netmgt.model.OnmsIpInterface)5 CannotCreateTransactionException (org.springframework.transaction.CannotCreateTransactionException)4 TransactionException (org.springframework.transaction.TransactionException)4 UnexpectedRollbackException (org.springframework.transaction.UnexpectedRollbackException)4 HashMap (java.util.HashMap)3 DataSource (javax.sql.DataSource)3 Before (org.junit.Before)3 OnmsNode (org.opennms.netmgt.model.OnmsNode)3 Connection (java.sql.Connection)2 Properties (java.util.Properties)2