org.springframework.transaction.PlatformTransactionManager Java Examples

The following examples show how to use org.springframework.transaction.PlatformTransactionManager. 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: IbisTransaction.java    From iaf with 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 #2
Source File: SampleDataLoader.java    From sakai with 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 File: TransactionManagerHolder.java    From framework with 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 File: SpringAwareUserTransaction.java    From alfresco-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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 #5
Source File: TransactionInterceptorTests.java    From spring-analysis-note with 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 #6
Source File: JdbcTemplateLockProvider.java    From ShedLock with 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 #7
Source File: TransactionalTestExecutionListenerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #8
Source File: DatabaseConfig.java    From cloudbreak with 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 #9
Source File: FlowableEngineConfig.java    From plumdo-work with 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 #10
Source File: AbstractTransactionAspectTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #11
Source File: AssetAdminService.java    From sample-boot-hibernate with 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 #12
Source File: JPAComponentProducer.java    From wildfly-camel-examples with Apache License 2.0 5 votes vote down vote up
@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 #13
Source File: SiteStatsPersistenceConfig.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@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 #14
Source File: AbstractTransactionAspectTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * 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 #15
Source File: TransactionAspectSupport.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public TransactionInfo(PlatformTransactionManager transactionManager,
		TransactionAttribute transactionAttribute, String joinpointIdentification) {

	this.transactionManager = transactionManager;
	this.transactionAttribute = transactionAttribute;
	this.joinpointIdentification = joinpointIdentification;
}
 
Example #16
Source File: TransactionInterceptorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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 #17
Source File: TransactionAspectSupport.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #18
Source File: TransactionManagerConfiguration.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Bean
@NoSynch
public PlatformTransactionManager transactionManager2() {
	CallCountingTransactionManager tm = new CallCountingTransactionManager();
	tm.setTransactionSynchronization(CallCountingTransactionManager.SYNCHRONIZATION_NEVER);
	return tm;
}
 
Example #19
Source File: UserDataSources.java    From secrets-proxy with 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 #20
Source File: TransactionManagerProducer.java    From wildfly-camel-examples with Apache License 2.0 5 votes vote down vote up
@Produces
@Named("jtaTransactionManager")
public PlatformTransactionManager createTransactionManager() {
    JtaTransactionManager jtaTransactionManager = new JtaTransactionManager();
    jtaTransactionManager.setUserTransaction(userTransaction);
    jtaTransactionManager.afterPropertiesSet();
    return jtaTransactionManager;
}
 
Example #21
Source File: TestBusinessDataSourceSelector.java    From EasyTransaction with Apache License 2.0 5 votes vote down vote up
@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 #22
Source File: UnitTestSupport.java    From sample-boot-hibernate with 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
Source File: TransactionManagerProducer.java    From wildfly-camel-examples with Apache License 2.0 5 votes vote down vote up
@Produces
@Named("transactionManager")
public PlatformTransactionManager createTransactionManager() {
    JtaTransactionManager jtaTransactionManager = new JtaTransactionManager();
    jtaTransactionManager.setUserTransaction(userTransaction);
    jtaTransactionManager.setTransactionManager(transactionManager);
    jtaTransactionManager.afterPropertiesSet();
    return jtaTransactionManager;
}
 
Example #24
Source File: TransactionInterceptor.java    From lams with 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 #25
Source File: TransactionAspectSupport.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
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 #26
Source File: MicroServiceTemplateSupport.java    From nh-micro with 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 #27
Source File: TransactionAttributeSourcePointcut.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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 #28
Source File: MicroServiceTemplateSupport.java    From nh-micro with 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 #29
Source File: SpringTransactionContextFactory.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
public SpringTransactionContextFactory(PlatformTransactionManager transactionManager, Integer transactionSynchronizationAdapterOrder) {
  this.transactionManager = transactionManager;
  this.transactionSynchronizationAdapterOrder = transactionSynchronizationAdapterOrder;
}
 
Example #30
Source File: SingleDataSourceSelector.java    From EasyTransaction with Apache License 2.0 4 votes vote down vote up
@Override
public PlatformTransactionManager selectTransactionManager(String appId, String busCode, long trxId) {
	return transactionManager;
}