Search in sources :

Example 1 with DefaultTransactionAttribute

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

the class TransactionAwareCacheDecoratorTests method putTransactional.

@Test
public void putTransactional() {
    Cache target = new ConcurrentMapCache("testCache");
    Cache cache = new TransactionAwareCacheDecorator(target);
    TransactionStatus status = txManager.getTransaction(new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED));
    Object key = new Object();
    cache.put(key, "123");
    assertNull(target.get(key));
    txManager.commit(status);
    assertEquals("123", target.get(key, String.class));
}
Also used : ConcurrentMapCache(org.springframework.cache.concurrent.ConcurrentMapCache) DefaultTransactionAttribute(org.springframework.transaction.interceptor.DefaultTransactionAttribute) TransactionStatus(org.springframework.transaction.TransactionStatus) ConcurrentMapCache(org.springframework.cache.concurrent.ConcurrentMapCache) Cache(org.springframework.cache.Cache) Test(org.junit.Test)

Example 2 with DefaultTransactionAttribute

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

the class LocalContainerEntityManagerFactoryBeanTests method testApplicationManagedEntityManagerWithJtaTransaction.

@Test
public void testApplicationManagedEntityManagerWithJtaTransaction() throws Exception {
    Object testEntity = new Object();
    // This one's for the tx (shared)
    EntityManager sharedEm = mock(EntityManager.class);
    given(sharedEm.getTransaction()).willReturn(new NoOpEntityTransaction());
    // This is the application-specific one
    EntityManager mockEm = mock(EntityManager.class);
    given(mockEmf.createEntityManager()).willReturn(sharedEm, mockEm);
    LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();
    MutablePersistenceUnitInfo pui = ((MutablePersistenceUnitInfo) cefb.getPersistenceUnitInfo());
    pui.setTransactionType(PersistenceUnitTransactionType.JTA);
    JpaTransactionManager jpatm = new JpaTransactionManager();
    jpatm.setEntityManagerFactory(cefb.getObject());
    TransactionStatus txStatus = jpatm.getTransaction(new DefaultTransactionAttribute());
    EntityManagerFactory emf = cefb.getObject();
    assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject());
    assertNotSame("EMF must be proxied", mockEmf, emf);
    EntityManager em = emf.createEntityManager();
    em.joinTransaction();
    assertFalse(em.contains(testEntity));
    jpatm.commit(txStatus);
    cefb.destroy();
    verify(mockEm).joinTransaction();
    verify(mockEm).contains(testEntity);
    verify(mockEmf).close();
}
Also used : EntityManager(javax.persistence.EntityManager) DefaultTransactionAttribute(org.springframework.transaction.interceptor.DefaultTransactionAttribute) EntityManagerFactory(javax.persistence.EntityManagerFactory) TransactionStatus(org.springframework.transaction.TransactionStatus) MutablePersistenceUnitInfo(org.springframework.orm.jpa.persistenceunit.MutablePersistenceUnitInfo) Test(org.junit.Test)

Example 3 with DefaultTransactionAttribute

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

the class SqlScriptsTestExecutionListener method executeSqlScripts.

/**
	 * Execute the SQL scripts configured via the supplied {@link Sql @Sql}
	 * annotation for the given {@link ExecutionPhase} and {@link TestContext}.
	 * <p>Special care must be taken in order to properly support the configured
	 * {@link SqlConfig#transactionMode}.
	 * @param sql the {@code @Sql} annotation to parse
	 * @param executionPhase the current execution phase
	 * @param testContext the current {@code TestContext}
	 * @param classLevel {@code true} if {@link Sql @Sql} was declared at the class level
	 */
private void executeSqlScripts(Sql sql, ExecutionPhase executionPhase, TestContext testContext, boolean classLevel) throws Exception {
    if (executionPhase != sql.executionPhase()) {
        return;
    }
    MergedSqlConfig mergedSqlConfig = new MergedSqlConfig(sql.config(), testContext.getTestClass());
    if (logger.isDebugEnabled()) {
        logger.debug(String.format("Processing %s for execution phase [%s] and test context %s.", mergedSqlConfig, executionPhase, testContext));
    }
    final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.setSqlScriptEncoding(mergedSqlConfig.getEncoding());
    populator.setSeparator(mergedSqlConfig.getSeparator());
    populator.setCommentPrefix(mergedSqlConfig.getCommentPrefix());
    populator.setBlockCommentStartDelimiter(mergedSqlConfig.getBlockCommentStartDelimiter());
    populator.setBlockCommentEndDelimiter(mergedSqlConfig.getBlockCommentEndDelimiter());
    populator.setContinueOnError(mergedSqlConfig.getErrorMode() == ErrorMode.CONTINUE_ON_ERROR);
    populator.setIgnoreFailedDrops(mergedSqlConfig.getErrorMode() == ErrorMode.IGNORE_FAILED_DROPS);
    String[] scripts = getScripts(sql, testContext, classLevel);
    scripts = TestContextResourceUtils.convertToClasspathResourcePaths(testContext.getTestClass(), scripts);
    List<Resource> scriptResources = TestContextResourceUtils.convertToResourceList(testContext.getApplicationContext(), scripts);
    for (String stmt : sql.statements()) {
        if (StringUtils.hasText(stmt)) {
            stmt = stmt.trim();
            scriptResources.add(new ByteArrayResource(stmt.getBytes(), "from inlined SQL statement: " + stmt));
        }
    }
    populator.setScripts(scriptResources.toArray(new Resource[scriptResources.size()]));
    if (logger.isDebugEnabled()) {
        logger.debug("Executing SQL scripts: " + ObjectUtils.nullSafeToString(scriptResources));
    }
    String dsName = mergedSqlConfig.getDataSource();
    String tmName = mergedSqlConfig.getTransactionManager();
    DataSource dataSource = TestContextTransactionUtils.retrieveDataSource(testContext, dsName);
    PlatformTransactionManager txMgr = TestContextTransactionUtils.retrieveTransactionManager(testContext, tmName);
    boolean newTxRequired = (mergedSqlConfig.getTransactionMode() == TransactionMode.ISOLATED);
    if (txMgr == null) {
        Assert.state(!newTxRequired, () -> String.format("Failed to execute SQL scripts for test context %s: " + "cannot execute SQL scripts using Transaction Mode " + "[%s] without a PlatformTransactionManager.", testContext, TransactionMode.ISOLATED));
        Assert.state(dataSource != null, () -> String.format("Failed to execute SQL scripts for test context %s: " + "supply at least a DataSource or PlatformTransactionManager.", testContext));
        // Execute scripts directly against the DataSource
        populator.execute(dataSource);
    } else {
        DataSource dataSourceFromTxMgr = getDataSourceFromTransactionManager(txMgr);
        // Ensure user configured an appropriate DataSource/TransactionManager pair.
        if (dataSource != null && dataSourceFromTxMgr != null && !dataSource.equals(dataSourceFromTxMgr)) {
            throw new IllegalStateException(String.format("Failed to execute SQL scripts for test context %s: " + "the configured DataSource [%s] (named '%s') is not the one associated with " + "transaction manager [%s] (named '%s').", testContext, dataSource.getClass().getName(), dsName, txMgr.getClass().getName(), tmName));
        }
        if (dataSource == null) {
            dataSource = dataSourceFromTxMgr;
            Assert.state(dataSource != null, () -> String.format("Failed to execute SQL scripts for " + "test context %s: could not obtain DataSource from transaction manager [%s] (named '%s').", testContext, txMgr.getClass().getName(), tmName));
        }
        final DataSource finalDataSource = dataSource;
        int propagation = (newTxRequired ? TransactionDefinition.PROPAGATION_REQUIRES_NEW : TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionAttribute txAttr = TestContextTransactionUtils.createDelegatingTransactionAttribute(testContext, new DefaultTransactionAttribute(propagation));
        new TransactionTemplate(txMgr, txAttr).execute(status -> {
            populator.execute(finalDataSource);
            return null;
        });
    }
}
Also used : TransactionAttribute(org.springframework.transaction.interceptor.TransactionAttribute) DefaultTransactionAttribute(org.springframework.transaction.interceptor.DefaultTransactionAttribute) DefaultTransactionAttribute(org.springframework.transaction.interceptor.DefaultTransactionAttribute) ResourceDatabasePopulator(org.springframework.jdbc.datasource.init.ResourceDatabasePopulator) ClassPathResource(org.springframework.core.io.ClassPathResource) ByteArrayResource(org.springframework.core.io.ByteArrayResource) Resource(org.springframework.core.io.Resource) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) ByteArrayResource(org.springframework.core.io.ByteArrayResource) PlatformTransactionManager(org.springframework.transaction.PlatformTransactionManager) DataSource(javax.sql.DataSource)

Example 4 with DefaultTransactionAttribute

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

the class LocalContainerEntityManagerFactoryBeanTests method testApplicationManagedEntityManagerWithTransactionAndCommitException.

@Test
public void testApplicationManagedEntityManagerWithTransactionAndCommitException() throws Exception {
    Object testEntity = new Object();
    EntityTransaction mockTx = mock(EntityTransaction.class);
    willThrow(new OptimisticLockException()).given(mockTx).commit();
    // This one's for the tx (shared)
    EntityManager sharedEm = mock(EntityManager.class);
    given(sharedEm.getTransaction()).willReturn(new NoOpEntityTransaction());
    // This is the application-specific one
    EntityManager mockEm = mock(EntityManager.class);
    given(mockEm.getTransaction()).willReturn(mockTx);
    given(mockEmf.createEntityManager()).willReturn(sharedEm, mockEm);
    LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();
    JpaTransactionManager jpatm = new JpaTransactionManager();
    jpatm.setEntityManagerFactory(cefb.getObject());
    TransactionStatus txStatus = jpatm.getTransaction(new DefaultTransactionAttribute());
    EntityManagerFactory emf = cefb.getObject();
    assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject());
    assertNotSame("EMF must be proxied", mockEmf, emf);
    EntityManager em = emf.createEntityManager();
    em.joinTransaction();
    assertFalse(em.contains(testEntity));
    try {
        jpatm.commit(txStatus);
        fail("Should have thrown OptimisticLockingFailureException");
    } catch (OptimisticLockingFailureException ex) {
    // expected
    }
    cefb.destroy();
    verify(mockTx).begin();
    verify(mockEm).contains(testEntity);
    verify(mockEmf).close();
}
Also used : EntityTransaction(javax.persistence.EntityTransaction) EntityManager(javax.persistence.EntityManager) OptimisticLockingFailureException(org.springframework.dao.OptimisticLockingFailureException) DefaultTransactionAttribute(org.springframework.transaction.interceptor.DefaultTransactionAttribute) EntityManagerFactory(javax.persistence.EntityManagerFactory) OptimisticLockException(javax.persistence.OptimisticLockException) TransactionStatus(org.springframework.transaction.TransactionStatus) Test(org.junit.Test)

Example 5 with DefaultTransactionAttribute

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

the class LocalContainerEntityManagerFactoryBeanTests method testApplicationManagedEntityManagerWithTransaction.

@Test
public void testApplicationManagedEntityManagerWithTransaction() throws Exception {
    Object testEntity = new Object();
    EntityTransaction mockTx = mock(EntityTransaction.class);
    // This one's for the tx (shared)
    EntityManager sharedEm = mock(EntityManager.class);
    given(sharedEm.getTransaction()).willReturn(new NoOpEntityTransaction());
    // This is the application-specific one
    EntityManager mockEm = mock(EntityManager.class);
    given(mockEm.getTransaction()).willReturn(mockTx);
    given(mockEmf.createEntityManager()).willReturn(sharedEm, mockEm);
    LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();
    JpaTransactionManager jpatm = new JpaTransactionManager();
    jpatm.setEntityManagerFactory(cefb.getObject());
    TransactionStatus txStatus = jpatm.getTransaction(new DefaultTransactionAttribute());
    EntityManagerFactory emf = cefb.getObject();
    assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject());
    assertNotSame("EMF must be proxied", mockEmf, emf);
    EntityManager em = emf.createEntityManager();
    em.joinTransaction();
    assertFalse(em.contains(testEntity));
    jpatm.commit(txStatus);
    cefb.destroy();
    verify(mockTx).begin();
    verify(mockTx).commit();
    verify(mockEm).contains(testEntity);
    verify(mockEmf).close();
}
Also used : EntityTransaction(javax.persistence.EntityTransaction) EntityManager(javax.persistence.EntityManager) DefaultTransactionAttribute(org.springframework.transaction.interceptor.DefaultTransactionAttribute) EntityManagerFactory(javax.persistence.EntityManagerFactory) TransactionStatus(org.springframework.transaction.TransactionStatus) Test(org.junit.Test)

Aggregations

DefaultTransactionAttribute (org.springframework.transaction.interceptor.DefaultTransactionAttribute)7 Test (org.junit.Test)6 TransactionStatus (org.springframework.transaction.TransactionStatus)6 EntityManager (javax.persistence.EntityManager)3 EntityManagerFactory (javax.persistence.EntityManagerFactory)3 Cache (org.springframework.cache.Cache)3 ConcurrentMapCache (org.springframework.cache.concurrent.ConcurrentMapCache)3 EntityTransaction (javax.persistence.EntityTransaction)2 OptimisticLockException (javax.persistence.OptimisticLockException)1 DataSource (javax.sql.DataSource)1 ByteArrayResource (org.springframework.core.io.ByteArrayResource)1 ClassPathResource (org.springframework.core.io.ClassPathResource)1 Resource (org.springframework.core.io.Resource)1 OptimisticLockingFailureException (org.springframework.dao.OptimisticLockingFailureException)1 ResourceDatabasePopulator (org.springframework.jdbc.datasource.init.ResourceDatabasePopulator)1 MutablePersistenceUnitInfo (org.springframework.orm.jpa.persistenceunit.MutablePersistenceUnitInfo)1 PlatformTransactionManager (org.springframework.transaction.PlatformTransactionManager)1 TransactionAttribute (org.springframework.transaction.interceptor.TransactionAttribute)1 TransactionTemplate (org.springframework.transaction.support.TransactionTemplate)1