Java Code Examples for org.springframework.transaction.support.TransactionTemplate#setPropagationBehavior()

The following examples show how to use org.springframework.transaction.support.TransactionTemplate#setPropagationBehavior() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DataSourceTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testTransactionWithPropagationNestedAndRollback() throws Exception {
	final TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive());

	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
			assertTrue("Is new transaction", status.isNewTransaction());
			status.setRollbackOnly();
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	verify(con).rollback();
	verify(con).close();
}
 
Example 2
Source File: TransactionRollbackDelegate.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(DelegateExecution execution) throws Exception {
  TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
  transactionTemplate.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRED);

  transactionTemplate.execute(new TransactionCallback<Void>() {

    @Override
    public Void doInTransaction(TransactionStatus status) {

      // simulate a failure that triggers the transaction rollback
      status.setRollbackOnly();

      return null;
    }
  });
}
 
Example 3
Source File: DataSourceTransactionManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testTransactionWithPropagationNested() throws Exception {
	final TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive());

	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
			assertTrue("Is new transaction", status.isNewTransaction());
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	verify(con).commit();
	verify(con).close();
}
 
Example 4
Source File: DataSourceTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testTransactionWithPropagationNever() throws Exception {
	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NEVER);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));

	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
			assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
			assertTrue("Is not new transaction", !status.isNewTransaction());
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
}
 
Example 5
Source File: JtaTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithNotSupportedExceptionOnNestedBegin() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);
	willThrow(new NotSupportedException("not supported")).given(ut).begin();

	try {
		JtaTransactionManager ptm = newJtaTransactionManager(ut);
		TransactionTemplate tt = new TransactionTemplate(ptm);
		tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED);
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				// something transactional
			}
		});
		fail("Should have thrown NestedTransactionNotSupportedException");
	}
	catch (NestedTransactionNotSupportedException ex) {
		// expected
	}
}
 
Example 6
Source File: JdoTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testTransactionCommitWithPropagationSupports() {
	given(pmf.getPersistenceManager()).willReturn(pm);

	PlatformTransactionManager tm = new JdoTransactionManager(pmf);
	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
	final List l = new ArrayList();
	l.add("test");
	assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf));

	Object result = tt.execute(new TransactionCallback() {
		@Override
		public Object doInTransaction(TransactionStatus status) {
			assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf));
			assertTrue("Is not new transaction", !status.isNewTransaction());
			PersistenceManagerFactoryUtils.getPersistenceManager(pmf, true);
			return l;
		}
	});
	assertTrue("Correct result list", result == l);

	assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf));

	verify(pm, times(2)).close();
}
 
Example 7
Source File: DataSourceTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testTransactionWithPropagationNested() throws Exception {
	final TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive());

	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
			assertTrue("Is new transaction", status.isNewTransaction());
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	verify(con).commit();
	verify(con).close();
}
 
Example 8
Source File: RdbEventRecordLoader.java    From DataLink with Apache License 2.0 6 votes vote down vote up
private boolean executeSql(DbDialect dbDialect, String sql) {
    TransactionTemplate transactionTemplate = dbDialect.getTransactionTemplate();
    int originalBehavior = transactionTemplate.getPropagationBehavior();

    try {
        transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
        return transactionTemplate.execute(transactionStatus -> {
            try {
                dbDialect.getJdbcTemplate().execute(new StatementCallback<Boolean>() {

                    public Boolean doInStatement(Statement stmt) throws SQLException, DataAccessException {
                        return stmt.execute(sql);
                    }
                });
                logger.info("Sql for adding-column is executed successfully : sql is {}", sql);
                return true;
            } catch (Throwable t) {
                logger.error(String.format("skip exception for adding-column-sql : sql is %s", sql), t);
            }
            return false;
        });
    } finally {
        transactionTemplate.setPropagationBehavior(originalBehavior);
    }
}
 
Example 9
Source File: JtaTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithPropagationSupportsAndSynchronizationNever() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	ptm.setTransactionSynchronization(JtaTransactionManager.SYNCHRONIZATION_NEVER);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
	ptm.afterPropertiesSet();

	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
}
 
Example 10
Source File: SpringTransactionInterceptor.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T execute(final CommandConfig config, final Command<T> command) {
    LOGGER.debug("Running command with propagation {}", config.getTransactionPropagation());


    // If the transaction is required (the other two options always need to go through the transactionTemplate),
    // the transactionTemplate is not used when the transaction is already active.
    // The reason for this is that the transactionTemplate try-catches exceptions and marks it as rollback.
    // Which will break nested service calls that go through the same stack of interceptors.

    int transactionPropagation = getPropagation(config);
    if (transactionPropagation == TransactionTemplate.PROPAGATION_REQUIRED && TransactionSynchronizationManager.isActualTransactionActive()) {
        return next.execute(config, command);

    } else {
        TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
        transactionTemplate.setPropagationBehavior(transactionPropagation);
        return transactionTemplate.execute(status -> next.execute(config, command));

    }

}
 
Example 11
Source File: JtaTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithPropagationSupports() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION);

	final TransactionSynchronization synch = mock(TransactionSynchronization.class);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			TransactionSynchronizationManager.registerSynchronization(synch);
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(synch).beforeCompletion();
	verify(synch).afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK);
}
 
Example 12
Source File: DataSourceTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testTransactionWithPropagationNestedAndRollback() throws Exception {
	final TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive());

	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
			assertTrue("Is new transaction", status.isNewTransaction());
			status.setRollbackOnly();
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	verify(con).rollback();
	verify(con).close();
}
 
Example 13
Source File: CustomFieldService.java    From wallride with Apache License 2.0 5 votes vote down vote up
@Transactional(propagation = Propagation.NOT_SUPPORTED)
@CacheEvict(value = WallRideCacheConfiguration.CUSTOM_FIELD_CACHE, allEntries = true)
public List<CustomField> bulkDeleteCustomField(CustomFieldBulkDeleteRequest bulkDeleteRequest, final BindingResult result) {
	List<CustomField> customFields = new ArrayList<>();
	for (long id : bulkDeleteRequest.getIds()) {
		final CustomFieldDeleteRequest deleteRequest = new CustomFieldDeleteRequest.Builder()
				.id(id)
				.language(bulkDeleteRequest.getLanguage())
				.build();

		final BeanPropertyBindingResult r = new BeanPropertyBindingResult(deleteRequest, "request");
		r.setMessageCodesResolver(messageCodesResolver);

		TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
		transactionTemplate.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW);
		CustomField customField = null;
		try {
			customField = transactionTemplate.execute(new TransactionCallback<CustomField>() {
				public CustomField doInTransaction(TransactionStatus status) {
					return deleteCustomField(deleteRequest, result);
				}
			});
			customFields.add(customField);
		} catch (Exception e) {
			logger.debug("Errors: {}", r);
			result.addAllErrors(r);
		}
	}
	return customFields;
}
 
Example 14
Source File: LocalDTSManager.java    From dtsopensource with Apache License 2.0 5 votes vote down vote up
@Override
public IDTSStore initStore() {
    jdbcTemplate = new JdbcTemplate(dataSource);
    transactionTemplate = new TransactionTemplate(new DataSourceTransactionManager(dataSource));
    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    return new LocalDTSStore(jdbcTemplate, transactionTemplate);
}
 
Example 15
Source File: SpringTransactionInterceptor.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public <T> T execute(final CommandConfig config, final Command<T> command) {
  LOGGER.debug("Running command with propagation {}", config.getTransactionPropagation());

  TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
  transactionTemplate.setPropagationBehavior(getPropagation(config));

  T result = transactionTemplate.execute(new TransactionCallback<T>() {
    public T doInTransaction(TransactionStatus status) {
      return next.execute(config, command);
    }
  });

  return result;
}
 
Example 16
Source File: DataSourceTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testTransactionWithIsolationAndReadOnly() throws Exception {
	given(con.getTransactionIsolation()).willReturn(Connection.TRANSACTION_READ_COMMITTED);
	given(con.getAutoCommit()).willReturn(true);

	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
	tt.setReadOnly(true);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			// something transactional
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	InOrder ordered = inOrder(con);
	ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
	ordered.verify(con).setAutoCommit(false);
	ordered.verify(con).commit();
	ordered.verify(con).setAutoCommit(true);
	ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
	verify(con).close();
}
 
Example 17
Source File: DataSourceTransactionManagerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testExistingTransactionWithManualSavepoint() throws Exception {
	DatabaseMetaData md = mock(DatabaseMetaData.class);
	Savepoint sp = mock(Savepoint.class);

	given(md.supportsSavepoints()).willReturn(true);
	given(con.getMetaData()).willReturn(md);
	given(con.setSavepoint("SAVEPOINT_1")).willReturn(sp);

	final TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive());

	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
			assertTrue("Is new transaction", status.isNewTransaction());
			Object savepoint = status.createSavepoint();
			status.releaseSavepoint(savepoint);
			assertTrue("Is new transaction", status.isNewTransaction());
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	verify(con).releaseSavepoint(sp);
	verify(con).commit();
	verify(con).close();
	verify(ds).getConnection();
}
 
Example 18
Source File: LocalDTSRule.java    From dtsopensource with Apache License 2.0 4 votes vote down vote up
@PostConstruct
public void init() {
    jdbcTemplate = new JdbcTemplate(dataSource);
    transactionTemplate = new TransactionTemplate(new DataSourceTransactionManager(dataSource));
    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
}
 
Example 19
Source File: LocalJobTrackerDelegate.java    From dubbox with Apache License 2.0 4 votes vote down vote up
private void initLocalDTSSchedule() {
	JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
	TransactionTemplate transactionTemplate = new TransactionTemplate(new DataSourceTransactionManager(dataSource));
	transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	localDTSSchedule = new LocalDTSSchedule(jdbcTemplate, transactionTemplate);
}
 
Example 20
Source File: ConcurrentJob.java    From rice with Educational Community License v2.0 4 votes vote down vote up
/**
 * Helper method for creating a TransactionTemplate initialized to create
 * a new transaction
 * @return a TransactionTemplate initialized to create a new transaction
 */
protected TransactionTemplate createNewTransaction() {
    TransactionTemplate tt = new TransactionTemplate(txManager);
    tt.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW);
    return tt;
}