Java Code Examples for org.springframework.transaction.PlatformTransactionManager

The following examples show how to use org.springframework.transaction.PlatformTransactionManager. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
@Test  // SPR-13895
public void transactionalTestWithoutTransactionManager() throws Exception {
	TransactionalTestExecutionListener listener = new TransactionalTestExecutionListener() {
		protected PlatformTransactionManager getTransactionManager(TestContext testContext, String qualifier) {
			return null;
		}
	};

	Class<? extends Invocable> clazz = TransactionalDeclaredOnClassLocallyTestCase.class;
	BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(clazz);
	Invocable instance = BeanUtils.instantiateClass(clazz);
	given(testContext.getTestInstance()).willReturn(instance);
	given(testContext.getTestMethod()).willReturn(clazz.getDeclaredMethod("transactionalTest"));

	assertFalse("callback should not have been invoked", instance.invoked());
	TransactionContextHolder.removeCurrentTransactionContext();

	try {
		listener.beforeTestMethod(testContext);
		fail("Should have thrown an IllegalStateException");
	}
	catch (IllegalStateException e) {
		assertTrue(e.getMessage().startsWith(
				"Failed to retrieve PlatformTransactionManager for @Transactional test"));
	}
}
 
Example 2
Source Project: sakai   Source File: SampleDataLoader.java    License: Educational Community License v2.0 6 votes vote down vote up
public void init() {
	log.info("Initializing " + getClass().getName());
	if(cmAdmin == null) {
		return;
	}
	if(loadSampleData) {
		loginToSakai();
		PlatformTransactionManager tm = (PlatformTransactionManager)beanFactory.getBean("org.sakaiproject.springframework.orm.hibernate.GlobalTransactionManager");
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		TransactionStatus status = tm.getTransaction(def);
		try {
			load();
		} catch (Exception e) {
			log.error("Unable to load CM data: " + e);
			tm.rollback(status);
		} finally {
			if(!status.isCompleted()) {
				tm.commit(status);
			}
		}
		logoutFromSakai();
	} else {
		if(log.isInfoEnabled()) log.info("Skipped CM data load");
	}
}
 
Example 3
Source Project: framework   Source File: TransactionManagerHolder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Description: 获取Spring trascation <br>
 * 
 * @author 王伟<br>
 * @taskId <br>
 * @return <br>
 */
public static PlatformTransactionManager getTransactionManager() {

    synchronized (transactionManagerHolder) {
        String dbCode = DynamicDataSourceManager.getDataSourceCode();
        PlatformTransactionManager manager = transactionManagerHolder.get(dbCode);

        if (manager == null) {
            HibernateTransactionManager hibernateTransactionManager = new HibernateTransactionManager();
            hibernateTransactionManager.setSessionFactory(getSessionFactory());
            manager = hibernateTransactionManager;
            transactionManagerHolder.put(dbCode, manager);
        }

        return manager;
    }
}
 
Example 4
Source Project: spring-analysis-note   Source File: TransactionInterceptorTests.java    License: MIT License 6 votes vote down vote up
@Test
public void determineTransactionManagerWithBeanNameSeveralTimes() {
	BeanFactory beanFactory = mock(BeanFactory.class);
	TransactionInterceptor ti = transactionInterceptorWithTransactionManagerName(
			"fooTransactionManager", beanFactory);

	PlatformTransactionManager txManager = 	associateTransactionManager(beanFactory, "fooTransactionManager");

	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("fooTransactionManager", PlatformTransactionManager.class);
}
 
Example 5
Source Project: ShedLock   Source File: JdbcTemplateLockProvider.java    License: Apache License 2.0 6 votes vote down vote up
Configuration(
    @NonNull JdbcTemplate jdbcTemplate,
    @Nullable PlatformTransactionManager transactionManager,
    @NonNull String tableName,
    @Nullable TimeZone timeZone,
    @NonNull ColumnNames columnNames,
    @NonNull String lockedByValue,
    boolean useDbTime
) {

    this.jdbcTemplate = requireNonNull(jdbcTemplate, "jdbcTemplate can not be null");
    this.transactionManager = transactionManager;
    this.tableName = requireNonNull(tableName, "tableName can not be null");
    this.timeZone = timeZone;
    this.columnNames = requireNonNull(columnNames, "columnNames can not be null");
    this.lockedByValue = requireNonNull(lockedByValue, "lockedByValue can not be null");
    if (useDbTime && timeZone != null) {
        throw new IllegalArgumentException("Can not set both useDbTime and timeZone");
    }
    this.useDbTime = useDbTime;
}
 
Example 6
/**
 * Creates a user transaction that defaults to {@link TransactionDefinition#PROPAGATION_REQUIRED}.
 * 
 * @param transactionManager the transaction manager to use
 * @param readOnly true to force a read-only transaction
 * @param isolationLevel one of the
 *      {@link TransactionDefinition#ISOLATION_DEFAULT TransactionDefinition.ISOLATION_XXX}
 *      constants
 * @param propagationBehaviour one of the
 *      {@link TransactionDefinition#PROPAGATION_MANDATORY TransactionDefinition.PROPAGATION__XXX}
 *      constants
 * @param timeout the transaction timeout in seconds.
 * 
 * @see TransactionDefinition#getTimeout()
 */
public SpringAwareUserTransaction(
        PlatformTransactionManager transactionManager,
        boolean readOnly,
        int isolationLevel,
        int propagationBehaviour,
        int timeout)
{
    super();
    setTransactionManager(transactionManager);
    setTransactionAttributeSource(this);
    this.readOnly = readOnly;
    this.isolationLevel = isolationLevel;
    this.propagationBehaviour = propagationBehaviour;
    this.timeout = timeout;
}
 
Example 7
Source Project: iaf   Source File: IbisTransaction.java    License: Apache License 2.0 6 votes vote down vote up
public IbisTransaction(PlatformTransactionManager txManager, TransactionDefinition txDef, String object) {
	this.txManager = txManager;
	this.txDef = txDef;
	this.object = object;

	txClientIsActive = TransactionSynchronizationManager.isActualTransactionActive();
	txClientName = TransactionSynchronizationManager.getCurrentTransactionName();

	txStatus = txManager.getTransaction(txDef);

	txIsActive = TransactionSynchronizationManager.isActualTransactionActive();
	txIsNew = txStatus.isNewTransaction();

	if (txIsNew) {
		txName = Misc.createSimpleUUID();
		TransactionSynchronizationManager.setCurrentTransactionName(txName);
		int txTimeout = txDef.getTimeout();
		log.debug("Transaction manager ["+getRealTransactionManager()+"] created a new transaction ["+txName+"] for " + object + " with timeout [" + (txTimeout<0?"system default(=120s)":""+txTimeout) + "]");
	} else {
		txName = TransactionSynchronizationManager.getCurrentTransactionName();
		if (txClientIsActive && !txIsActive) {
			log.debug("Transaction manager ["+getRealTransactionManager()+"] suspended the transaction [" + txClientName + "] for " + object);
		}
	}
}
 
Example 8
/**
 * Simulate a transaction infrastructure failure.
 * Shouldn't invoke target method.
 */
@Test
public void cannotCreateTransaction() throws Exception {
	TransactionAttribute txatt = new DefaultTransactionAttribute();

	Method m = getNameMethod;
	MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
	tas.register(m, txatt);

	PlatformTransactionManager ptm = mock(PlatformTransactionManager.class);
	// Expect a transaction
	CannotCreateTransactionException ex = new CannotCreateTransactionException("foobar", null);
	given(ptm.getTransaction(txatt)).willThrow(ex);

	TestBean tb = new TestBean() {
		@Override
		public String getName() {
			throw new UnsupportedOperationException(
					"Shouldn't have invoked target method when couldn't create transaction for transactional method");
		}
	};
	ITestBean itb = (ITestBean) advised(tb, ptm, tas);

	try {
		itb.getName();
		fail("Shouldn't have invoked method");
	}
	catch (CannotCreateTransactionException thrown) {
		assertTrue(thrown == ex);
	}
}
 
Example 9
@Bean(name = "org.sakaiproject.sitestats.SiteStatsTransactionManager")
public PlatformTransactionManager getSiteStatsTransactionManager() throws IOException {
    if (siteStatsTransactionManager == null) {
        String whichDb = serverConfigurationService.getString("sitestats.db", "internal");
        if ("external".equals(whichDb)) {
            HibernateTransactionManager tx = new HibernateTransactionManager();
            tx.setSessionFactory(getSiteStatsSessionFactory());
            siteStatsTransactionManager = tx;
        } else {
            siteStatsTransactionManager = globalTransactionManager;
        }
    }
    return siteStatsTransactionManager;
}
 
Example 10
/**
 * Test that TransactionStatus.setRollbackOnly works.
 */
@Test
public void programmaticRollback() throws Exception {
	TransactionAttribute txatt = new DefaultTransactionAttribute();

	Method m = getNameMethod;
	MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
	tas.register(m, txatt);

	TransactionStatus status = mock(TransactionStatus.class);
	PlatformTransactionManager ptm = mock(PlatformTransactionManager.class);

	given(ptm.getTransaction(txatt)).willReturn(status);

	final String name = "jenny";
	TestBean tb = new TestBean() {
		@Override
		public String getName() {
			TransactionStatus txStatus = TransactionInterceptor.currentTransactionStatus();
			txStatus.setRollbackOnly();
			return name;
		}
	};

	ITestBean itb = (ITestBean) advised(tb, ptm, tas);

	// verification!?
	assertTrue(name.equals(itb.getName()));

	verify(ptm).commit(status);
}
 
Example 11
public TransactionInfo(PlatformTransactionManager transactionManager,
		TransactionAttribute transactionAttribute, String joinpointIdentification) {

	this.transactionManager = transactionManager;
	this.transactionAttribute = transactionAttribute;
	this.joinpointIdentification = joinpointIdentification;
}
 
Example 12
Source Project: cloudbreak   Source File: DatabaseConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public PlatformTransactionManager transactionManager() throws SQLException {
    JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
    jpaTransactionManager.setEntityManagerFactory(entityManagerFactory());
    jpaTransactionManager.afterPropertiesSet();
    return jpaTransactionManager;
}
 
Example 13
Source Project: plumdo-work   Source File: FlowableEngineConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public SpringProcessEngineConfiguration springProcessEngineConfiguration(DataSource dataSource, PlatformTransactionManager platformTransactionManager, ObjectProvider<AsyncExecutor> asyncExecutorProvider)
        throws IOException {
    SpringProcessEngineConfiguration conf = super.springProcessEngineConfiguration(dataSource, platformTransactionManager, asyncExecutorProvider);
    String databaseSchema = conf.getDatabaseSchema();
    conf.setDatabaseCatalog(databaseSchema);
    conf.setDatabaseTablePrefix(databaseSchema + ".");
    conf.setTablePrefixIsSchema(true);
    conf.setActivityFontName("黑体");
    conf.setLabelFontName("黑体");
    conf.setAnnotationFontName("黑体");
    return conf;
}
 
Example 14
@Bean
@NoSynch
public PlatformTransactionManager transactionManager2() {
	CallCountingTransactionManager tm = new CallCountingTransactionManager();
	tm.setTransactionSynchronization(CallCountingTransactionManager.SYNCHRONIZATION_NEVER);
	return tm;
}
 
Example 15
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;
}
 
Example 16
Source Project: nh-micro   Source File: MicroServiceTemplateSupport.java    License: Apache License 2.0 5 votes vote down vote up
public void dbTranNestRollback() throws Exception{
	PlatformTransactionManager  transactionManager=MicroTranManagerHolder.getTransactionManager(dbName);
    DefaultTransactionDefinition def =new DefaultTransactionDefinition();
    def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionStatus status=transactionManager.getTransaction(def);
    transactionManager.rollback(status);

}
 
Example 17
@Produces
@Named("jtaTransactionManager")
public PlatformTransactionManager createTransactionManager() {
    JtaTransactionManager jtaTransactionManager = new JtaTransactionManager();
    jtaTransactionManager.setUserTransaction(userTransaction);
    jtaTransactionManager.afterPropertiesSet();
    return jtaTransactionManager;
}
 
Example 18
Source Project: nh-micro   Source File: MicroServiceTemplateSupport.java    License: Apache License 2.0 5 votes vote down vote up
public Integer getSeqByMysql(String seqKey){

		PlatformTransactionManager  transactionManager=MicroTranManagerHolder.getTransactionManager(dbName);
	    DefaultTransactionDefinition def =new DefaultTransactionDefinition();
	    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	    TransactionStatus status=transactionManager.getTransaction(def);
	    try
	    {
			String sql="select get_micro_seq('"+seqKey+"') as seq";
			List retList=getInnerDao().queryObjJoinByCondition(sql);
			if(retList==null){
				transactionManager.commit(status);
				return null;
			}
			Map retMap=(Map) retList.get(0);
			Integer seq=(Integer) retMap.get("seq");
			transactionManager.commit(status);
			return seq;	    	
	    }
	    catch(Exception ex)
	    {
	    	transactionManager.rollback(status);
	        throw new RuntimeException("getseq error",ex);
	    }


	}
 
Example 19
@Override
public boolean matches(Method method, Class<?> targetClass) {
	if (TransactionalProxy.class.isAssignableFrom(targetClass) ||
			PlatformTransactionManager.class.isAssignableFrom(targetClass) ||
			PersistenceExceptionTranslator.class.isAssignableFrom(targetClass)) {
		return false;
	}
	TransactionAttributeSource tas = getTransactionAttributeSource();
	return (tas == null || tas.getTransactionAttribute(method, targetClass) != null);
}
 
Example 20
Source Project: lams   Source File: TransactionInterceptor.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
	// Rely on default serialization, although this class itself doesn't carry state anyway...
	ois.defaultReadObject();

	// Serialize all relevant superclass fields.
	// Superclass can't implement Serializable because it also serves as base class
	// for AspectJ aspects (which are not allowed to implement Serializable)!
	setTransactionManagerBeanName((String) ois.readObject());
	setTransactionManager((PlatformTransactionManager) ois.readObject());
	setTransactionAttributeSource((TransactionAttributeSource) ois.readObject());
	setBeanFactory((BeanFactory) ois.readObject());
}
 
Example 21
@Produces
@Named("transactionManager")
public PlatformTransactionManager createTransactionManager() {
    JtaTransactionManager jtaTransactionManager = new JtaTransactionManager();
    jtaTransactionManager.setUserTransaction(userTransaction);
    jtaTransactionManager.setTransactionManager(transactionManager);
    jtaTransactionManager.afterPropertiesSet();
    return jtaTransactionManager;
}
 
Example 22
Source Project: sample-boot-hibernate   Source File: UnitTestSupport.java    License: MIT License 5 votes vote down vote up
protected void tx(PlatformTransactionManager txm, Runnable command) {
    tx(txm, () -> {
        command.run();
        rep.flush();
        return true;
    });
}
 
Example 23
@Override
public PlatformTransactionManager selectTransactionManager(String appId, String busCode, EasyTransRequest<?, ?> request) {
	if(appId != null){
		busCode = busCode.replace("Cascade", "");
		busCode = busCode.replace("sagaP", "p");
		return ctx.getBean(busCode+"TransactionManager", PlatformTransactionManager.class);
	}else{
		return ctx.getBean("wholeTransactionManager", PlatformTransactionManager.class);
	}
}
 
Example 24
Source Project: sample-boot-hibernate   Source File: AssetAdminService.java    License: MIT License 5 votes vote down vote up
public AssetAdminService(
        DefaultRepository rep,
        PlatformTransactionManager txm,
        AuditHandler audit,
        IdLockHandler idLock) {
    this.rep = rep;
    this.txm = txm;
    this.audit = audit;
    this.idLock = idLock;
}
 
Example 25
Source Project: secrets-proxy   Source File: UserDataSources.java    License: Apache License 2.0 5 votes vote down vote up
private DSLContext getDslContext(PlatformTransactionManager txManager, DataSource dataSource) {
  DefaultConfiguration config = new DefaultConfiguration();
  config.set(new DataSourceConnectionProvider(new TransactionAwareDataSourceProxy(dataSource)));
  config.set(new DefaultExecuteListenerProvider(new JooqExceptionTranslator()));
  config.set(new SpringTransactionProvider(txManager));
  return new DefaultDSLContext(config);
}
 
Example 26
@Produces
@ApplicationScoped
@Named("jpa")
public JpaComponent jpaComponent(PlatformTransactionManager transactionManager, EntityManager entityManager) {
    JpaComponent component = new JpaComponent();
    component.setTransactionManager(transactionManager);
    component.setEntityManagerFactory(entityManager.getEntityManagerFactory());
    return component;
}
 
Example 27
/**
 * Prepare a TransactionInfo for the given attribute and status object.
 * @param txAttr the TransactionAttribute (may be {@code null})
 * @param joinpointIdentification the fully qualified method name
 * (used for monitoring and logging purposes)
 * @param status the TransactionStatus for the current transaction
 * @return the prepared TransactionInfo object
 */
protected TransactionInfo prepareTransactionInfo(PlatformTransactionManager tm,
		TransactionAttribute txAttr, String joinpointIdentification, TransactionStatus status) {

	TransactionInfo txInfo = new TransactionInfo(tm, txAttr, joinpointIdentification);
	if (txAttr != null) {
		// We need a transaction for this method
		if (logger.isTraceEnabled()) {
			logger.trace("Getting transaction for [" + txInfo.getJoinpointIdentification() + "]");
		}
		// The transaction manager will flag an error if an incompatible tx already exists
		txInfo.newTransactionStatus(status);
	}
	else {
		// The TransactionInfo.hasTransaction() method will return
		// false. We created it only to preserve the integrity of
		// the ThreadLocal stack maintained in this class.
		if (logger.isTraceEnabled())
			logger.trace("Don't need to create transaction for [" + joinpointIdentification +
					"]: This method isn't transactional.");
	}

	// We always bind the TransactionInfo to the thread, even if we didn't create
	// a new transaction here. This guarantees that the TransactionInfo stack
	// will be managed correctly even if no transaction was created by this aspect.
	txInfo.bindToThread();
	return txInfo;
}
 
Example 28
@Test
public void determineTransactionManagerWithEmptyQualifierAndDefaultName() {
	BeanFactory beanFactory = mock(BeanFactory.class);
	PlatformTransactionManager defaultTransactionManager
			= associateTransactionManager(beanFactory, "defaultTransactionManager");
	TransactionInterceptor ti = transactionInterceptorWithTransactionManagerName(
			"defaultTransactionManager", beanFactory);

	DefaultTransactionAttribute attribute = new DefaultTransactionAttribute();
	attribute.setQualifier("");

	assertSame(defaultTransactionManager, ti.determineTransactionManager(attribute));
}
 
Example 29
/**
 * 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[0]));
	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;
		});
	}
}
 
Example 30
@Bean
public PlatformTransactionManager transactionManager() {
	return txManager;
}