Search in sources :

Example 6 with TransactionStatus

use of org.springframework.transaction.TransactionStatus in project jOOQ by jOOQ.

the class TransactionTest method testExplicitTransactions.

@Test
public void testExplicitTransactions() {
    boolean rollback = false;
    TransactionStatus tx = txMgr.getTransaction(new DefaultTransactionDefinition());
    try {
        // constraint violation exception
        for (int i = 0; i < 2; i++) dsl.insertInto(BOOK).set(BOOK.ID, 5).set(BOOK.AUTHOR_ID, 1).set(BOOK.TITLE, "Book 5").execute();
        Assert.fail();
    }// Upon the constraint violation, we explicitly roll back the transaction.
     catch (DataAccessException e) {
        txMgr.rollback(tx);
        rollback = true;
    }
    assertEquals(4, dsl.fetchCount(BOOK));
    assertTrue(rollback);
}
Also used : DefaultTransactionDefinition(org.springframework.transaction.support.DefaultTransactionDefinition) TransactionStatus(org.springframework.transaction.TransactionStatus) DataAccessException(org.springframework.dao.DataAccessException) Test(org.junit.Test)

Example 7 with TransactionStatus

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

the class SchedulerAccessor method registerJobsAndTriggers.

/**
	 * Register jobs and triggers (within a transaction, if possible).
	 */
protected void registerJobsAndTriggers() throws SchedulerException {
    TransactionStatus transactionStatus = null;
    if (this.transactionManager != null) {
        transactionStatus = this.transactionManager.getTransaction(new DefaultTransactionDefinition());
    }
    try {
        if (this.jobSchedulingDataLocations != null) {
            ClassLoadHelper clh = new ResourceLoaderClassLoadHelper(this.resourceLoader);
            clh.initialize();
            XMLSchedulingDataProcessor dataProcessor = new XMLSchedulingDataProcessor(clh);
            for (String location : this.jobSchedulingDataLocations) {
                dataProcessor.processFileAndScheduleJobs(location, getScheduler());
            }
        }
        // Register JobDetails.
        if (this.jobDetails != null) {
            for (JobDetail jobDetail : this.jobDetails) {
                addJobToScheduler(jobDetail);
            }
        } else {
            // Create empty list for easier checks when registering triggers.
            this.jobDetails = new LinkedList<>();
        }
        // Register Calendars.
        if (this.calendars != null) {
            for (String calendarName : this.calendars.keySet()) {
                Calendar calendar = this.calendars.get(calendarName);
                getScheduler().addCalendar(calendarName, calendar, true, true);
            }
        }
        // Register Triggers.
        if (this.triggers != null) {
            for (Trigger trigger : this.triggers) {
                addTriggerToScheduler(trigger);
            }
        }
    } catch (Throwable ex) {
        if (transactionStatus != null) {
            try {
                this.transactionManager.rollback(transactionStatus);
            } catch (TransactionException tex) {
                logger.error("Job registration exception overridden by rollback exception", ex);
                throw tex;
            }
        }
        if (ex instanceof SchedulerException) {
            throw (SchedulerException) ex;
        }
        if (ex instanceof Exception) {
            throw new SchedulerException("Registration of jobs and triggers failed: " + ex.getMessage(), ex);
        }
        throw new SchedulerException("Registration of jobs and triggers failed: " + ex.getMessage());
    }
    if (transactionStatus != null) {
        this.transactionManager.commit(transactionStatus);
    }
}
Also used : DefaultTransactionDefinition(org.springframework.transaction.support.DefaultTransactionDefinition) SchedulerException(org.quartz.SchedulerException) XMLSchedulingDataProcessor(org.quartz.xml.XMLSchedulingDataProcessor) Calendar(org.quartz.Calendar) TransactionStatus(org.springframework.transaction.TransactionStatus) ClassLoadHelper(org.quartz.spi.ClassLoadHelper) SchedulerException(org.quartz.SchedulerException) ObjectAlreadyExistsException(org.quartz.ObjectAlreadyExistsException) TransactionException(org.springframework.transaction.TransactionException) JobDetail(org.quartz.JobDetail) Trigger(org.quartz.Trigger) TransactionException(org.springframework.transaction.TransactionException)

Example 8 with TransactionStatus

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

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

the class DataSourceTransactionManagerTests method testParticipatingTransactionWithRollbackOnlyAndInnerSynch.

@Test
public void testParticipatingTransactionWithRollbackOnlyAndInnerSynch() throws Exception {
    tm.setTransactionSynchronization(DataSourceTransactionManager.SYNCHRONIZATION_NEVER);
    DataSourceTransactionManager tm2 = new DataSourceTransactionManager(ds);
    // tm has no synch enabled (used at outer level), tm2 has synch enabled (inner level)
    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
    assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive());
    TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
    final TestTransactionSynchronization synch = new TestTransactionSynchronization(ds, TransactionSynchronization.STATUS_UNKNOWN);
    try {
        assertTrue("Is new transaction", ts.isNewTransaction());
        final TransactionTemplate tt = new TransactionTemplate(tm2);
        tt.execute(new TransactionCallbackWithoutResult() {

            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
                assertTrue("Is existing transaction", !status.isNewTransaction());
                assertFalse("Is not rollback-only", status.isRollbackOnly());
                tt.execute(new TransactionCallbackWithoutResult() {

                    @Override
                    protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
                        assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds));
                        assertTrue("Synchronization active", TransactionSynchronizationManager.isSynchronizationActive());
                        assertTrue("Is existing transaction", !status.isNewTransaction());
                        status.setRollbackOnly();
                    }
                });
                assertTrue("Is existing transaction", !status.isNewTransaction());
                assertTrue("Is rollback-only", status.isRollbackOnly());
                TransactionSynchronizationManager.registerSynchronization(synch);
            }
        });
        tm.commit(ts);
        fail("Should have thrown UnexpectedRollbackException");
    } catch (UnexpectedRollbackException ex) {
    // expected
    }
    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
    assertFalse(synch.beforeCommitCalled);
    assertTrue(synch.beforeCompletionCalled);
    assertFalse(synch.afterCommitCalled);
    assertTrue(synch.afterCompletionCalled);
    verify(con).rollback();
    verify(con).close();
}
Also used : DefaultTransactionDefinition(org.springframework.transaction.support.DefaultTransactionDefinition) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) TransactionStatus(org.springframework.transaction.TransactionStatus) UnexpectedRollbackException(org.springframework.transaction.UnexpectedRollbackException) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult) Test(org.junit.Test)

Example 10 with TransactionStatus

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

the class DataSourceTransactionManagerTests method doTestTransactionWithTimeout.

private void doTestTransactionWithTimeout(int timeout) throws Exception {
    Assume.group(TestGroup.PERFORMANCE);
    PreparedStatement ps = mock(PreparedStatement.class);
    given(con.getAutoCommit()).willReturn(true);
    given(con.prepareStatement("some SQL statement")).willReturn(ps);
    TransactionTemplate tt = new TransactionTemplate(tm);
    tt.setTimeout(timeout);
    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
    try {
        tt.execute(new TransactionCallbackWithoutResult() {

            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                try {
                    Thread.sleep(1500);
                } catch (InterruptedException ex) {
                }
                try {
                    Connection con = DataSourceUtils.getConnection(ds);
                    PreparedStatement ps = con.prepareStatement("some SQL statement");
                    DataSourceUtils.applyTransactionTimeout(ps, ds);
                } catch (SQLException ex) {
                    throw new DataAccessResourceFailureException("", ex);
                }
            }
        });
        if (timeout <= 1) {
            fail("Should have thrown TransactionTimedOutException");
        }
    } catch (TransactionTimedOutException ex) {
        if (timeout <= 1) {
        // expected
        } else {
            throw ex;
        }
    }
    assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
    if (timeout > 1) {
        verify(ps).setQueryTimeout(timeout - 1);
        verify(con).commit();
    } else {
        verify(con).rollback();
    }
    InOrder ordered = inOrder(con);
    ordered.verify(con).setAutoCommit(false);
    ordered.verify(con).setAutoCommit(true);
    verify(con).close();
}
Also used : TransactionTimedOutException(org.springframework.transaction.TransactionTimedOutException) InOrder(org.mockito.InOrder) UncategorizedSQLException(org.springframework.jdbc.UncategorizedSQLException) SQLException(java.sql.SQLException) DataAccessResourceFailureException(org.springframework.dao.DataAccessResourceFailureException) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) Connection(java.sql.Connection) TransactionStatus(org.springframework.transaction.TransactionStatus) PreparedStatement(java.sql.PreparedStatement) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult)

Aggregations

TransactionStatus (org.springframework.transaction.TransactionStatus)340 Test (org.junit.Test)179 TransactionCallbackWithoutResult (org.springframework.transaction.support.TransactionCallbackWithoutResult)151 TransactionCallback (org.springframework.transaction.support.TransactionCallback)85 TransactionTemplate (org.springframework.transaction.support.TransactionTemplate)70 DefaultTransactionDefinition (org.springframework.transaction.support.DefaultTransactionDefinition)32 ArrayList (java.util.ArrayList)30 List (java.util.List)26 SQLException (java.sql.SQLException)24 Connection (java.sql.Connection)21 Date (java.util.Date)21 PreparedStatement (java.sql.PreparedStatement)17 TransactionSynchronizationAdapter (org.springframework.transaction.support.TransactionSynchronizationAdapter)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 CaseInsensitiveString (com.thoughtworks.go.config.CaseInsensitiveString)10