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

The following examples show how to use org.springframework.transaction.support.DefaultTransactionDefinition#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: MicroServiceTemplateSupport.java    From nh-micro with Apache License 2.0 6 votes vote down vote up
public Object execGroovyRetObjByDbTran(String groovyName, String methodName,
			Object... paramArray) throws Exception{
/*		MicroMetaDao microDao=MicroMetaDao.getInstance(dbName,dbType);
		DataSource dataSource=microDao.getMicroDataSource();
		PlatformTransactionManager  transactionManager=new DataSourceTransactionManager(dataSource);*/
		PlatformTransactionManager  transactionManager=MicroTranManagerHolder.getTransactionManager(dbName);
	    DefaultTransactionDefinition def =new DefaultTransactionDefinition();
	    def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
	    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	    TransactionStatus status=transactionManager.getTransaction(def);
	    try
	    {
	    	Object retObj= GroovyExecUtil.execGroovyRetObj(groovyName, methodName, paramArray);
	    	transactionManager.commit(status);
	    	return retObj;
	    }
	    catch(Exception ex)
	    {
	    	transactionManager.rollback(status);
	        throw ex;
	    }
		
	}
 
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: MicroServiceTemplateSupport.java    From nh-micro with Apache License 2.0 6 votes vote down vote up
public Object execGroovyRetObjByDbTran(String groovyName, String methodName,
			Object... paramArray) throws Exception{
/*		MicroMetaDao microDao=MicroMetaDao.getInstance(dbName,dbType);
		DataSource dataSource=microDao.getMicroDataSource();
		PlatformTransactionManager  transactionManager=new DataSourceTransactionManager(dataSource);*/
		PlatformTransactionManager  transactionManager=MicroTranManagerHolder.getTransactionManager(dbName);
	    DefaultTransactionDefinition def =new DefaultTransactionDefinition();
	    def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
	    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	    TransactionStatus status=transactionManager.getTransaction(def);
	    try
	    {
	    	Object retObj= GroovyExecUtil.execGroovyRetObj(groovyName, methodName, paramArray);
	    	transactionManager.commit(status);
	    	return retObj;
	    }
	    catch(Exception ex)
	    {
	    	transactionManager.rollback(status);
	        throw ex;
	    }
		
	}
 
Example 4
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 5
Source File: SpringJdbcTransactionOperations.java    From micronaut-data with Apache License 2.0 6 votes vote down vote up
@Override
public <R> R execute(@NonNull TransactionDefinition definition, @NonNull TransactionCallback<Connection, R> callback) {
    ArgumentUtils.requireNonNull("callback", callback);
    ArgumentUtils.requireNonNull("definition", definition);

    final DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setReadOnly(definition.isReadOnly());
    def.setIsolationLevel(definition.getIsolationLevel().getCode());
    def.setPropagationBehavior(definition.getPropagationBehavior().ordinal());
    def.setName(definition.getName());
    final Duration timeout = definition.getTimeout();
    if (!timeout.isNegative()) {
        def.setTimeout((int) timeout.getSeconds());
    }
    TransactionTemplate template = new TransactionTemplate(transactionManager, def);
    return template.execute(status -> {
                try {
                    return callback.call(new JdbcTransactionStatus(status));
                } catch (RuntimeException | Error ex) {
                    throw ex;
                } catch (Exception e) {
                    throw new UndeclaredThrowableException(e, "TransactionCallback threw undeclared checked exception");
                }
            }
    );
}
 
Example 6
Source File: WebSphereUowTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void propagationNeverFailsInCaseOfExistingTransaction() {
	MockUOWManager manager = new MockUOWManager();
	manager.setUOWStatus(UOWManager.UOW_STATUS_ACTIVE);
	WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager);
	DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
	definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_NEVER);

	try {
		ptm.execute(definition, new TransactionCallback<String>() {
			@Override
			public String doInTransaction(TransactionStatus status) {
				return "result";
			}
		});
		fail("Should have thrown IllegalTransactionStateException");
	}
	catch (IllegalTransactionStateException ex) {
		// expected
	}
}
 
Example 7
Source File: TransactionImpl.java    From cuba with Apache License 2.0 6 votes vote down vote up
public TransactionImpl(PlatformTransactionManager transactionManager, PersistenceImpl persistence, boolean join,
                       @Nullable TransactionParams params, String storeName) {
    this.tm = transactionManager;
    this.persistence = persistence;
    this.storeName = storeName;

    log.trace("Creating transaction: store='{}' join={} params={}", storeName, join, params);

    td = new DefaultTransactionDefinition();
    if (join)
        td.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    else
        td.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

    if (params != null) {
        if (params.getTimeout() != 0)
            td.setTimeout(params.getTimeout());
        if (params.isReadOnly())
            td.setReadOnly(true);
    }

    ts = tm.getTransaction(td);

    persistence.registerSynchronizations(storeName);
}
 
Example 8
Source File: WebSphereUowTransactionManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void propagationNeverFailsInCaseOfExistingTransaction() {
	MockUOWManager manager = new MockUOWManager();
	manager.setUOWStatus(UOWManager.UOW_STATUS_ACTIVE);
	WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager);
	DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
	definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_NEVER);

	try {
		ptm.execute(definition, new TransactionCallback<String>() {
			@Override
			public String doInTransaction(TransactionStatus status) {
				return "result";
			}
		});
		fail("Should have thrown IllegalTransactionStateException");
	}
	catch (IllegalTransactionStateException ex) {
		// expected
	}
}
 
Example 9
Source File: WebSphereUowTransactionManagerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void doTestNewTransactionSynchronization(int propagationBehavior, final int synchMode) {
	MockUOWManager manager = new MockUOWManager();
	WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager);
	ptm.setTransactionSynchronization(synchMode);
	DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
	definition.setPropagationBehavior(propagationBehavior);
	definition.setReadOnly(true);

	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
	assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());

	assertEquals("result", ptm.execute(definition, new TransactionCallback<String>() {
		@Override
		public String doInTransaction(TransactionStatus status) {
			if (synchMode == WebSphereUowTransactionManager.SYNCHRONIZATION_ALWAYS) {
				assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
				assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
				assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
			}
			else {
				assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
				assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
				assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
			}
			return "result";
		}
	}));

	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
	assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());

	assertEquals(0, manager.getUOWTimeout());
	assertEquals(UOWManager.UOW_TYPE_LOCAL_TRANSACTION, manager.getUOWType());
	assertFalse(manager.getJoined());
	assertFalse(manager.getRollbackOnly());
}
 
Example 10
Source File: MicroServiceTemplateSupport.java    From nh-micro with Apache License 2.0 5 votes vote down vote up
public void dbTranNestRollbackAndThrow() 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);
    throw new RuntimeException("dbTranNestRollbackAndThrow");

}
 
Example 11
Source File: MicroServiceTemplateSupport.java    From nh-micro with Apache License 2.0 5 votes vote down vote up
public void dbTranNestRollbackAndThrow() 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);
    throw new RuntimeException("dbTranNestRollbackAndThrow");

}
 
Example 12
Source File: SpringHibernateDataStore.java    From elide-spring-boot with Apache License 2.0 5 votes vote down vote up
@Override
public DataStoreTransaction beginTransaction() {
  // begin a spring transaction
  DefaultTransactionDefinition def = new DefaultTransactionDefinition();
  def.setName("elide transaction");
  def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
  TransactionStatus txStatus = txManager.getTransaction(def);

  Session session = entityManager.unwrap(Session.class);
  Preconditions.checkNotNull(session);

  return transactionSupplier.get(session, txManager, txStatus, isScrollEnabled, scrollMode);
}
 
Example 13
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 14
Source File: RetriableTransactionInterceptor.java    From HA-DB with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Around("@annotation(com.hitler.common.aop.annotation.RetriableTransaction)")
public Object retry(ProceedingJoinPoint pjp) throws Throwable {
	MethodSignature signature = (MethodSignature) pjp.getSignature();
	Method method = signature.getMethod();
	RetriableTransaction annotation = method.getAnnotation(RetriableTransaction.class);
	int maxAttempts = annotation.maxRetries();
	int attemptCount = 0;
	List<Class<? extends Throwable>> exceptions = Arrays.asList(annotation.retryFor());
	Throwable failure = null;
	TransactionStatus currentTransactionStatus = null;
	String businessName = pjp.getTarget().toString();
	businessName = businessName.substring(0, businessName.lastIndexOf("@")) + "." + method.getName();
	do {
		attemptCount++;
		try {
			DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
			transactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
			currentTransactionStatus = transactionManager.getTransaction(transactionDefinition);
			Object returnValue = pjp.proceed();
			transactionManager.commit(currentTransactionStatus);
			return returnValue;
		} catch (Throwable t) {
			if (!exceptions.contains(t.getClass())) {
				throw t;
			}
			if (currentTransactionStatus != null && !currentTransactionStatus.isCompleted()) {
				transactionManager.rollback(currentTransactionStatus);
				failure = t;
			}
			LOGGER.debug("事务重试:["+businessName+":"+attemptCount+"/"+maxAttempts+"]");
		}
	} while (attemptCount < maxAttempts);
	LOGGER.debug("事务重试:["+businessName+":已达最大重试次数]");
	throw failure;
}
 
Example 15
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 16
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 17
Source File: IndexPerformance.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public void loadLotsOfData() {
	DefaultTransactionDefinition def = new DefaultTransactionDefinition();
	def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
	TransactionStatus status = tm.getTransaction(def);
	
	try {
		String asId = "IndexPerf AS";
		cmAdmin.createAcademicSession(asId, asId, asId, null, null);
		
		String csId = "IndexPerf CS";
		cmAdmin.createCourseSet(csId, csId, csId, "DEPT", null);
		
		String ccId = "IndexPerf CC";
		cmAdmin.createCanonicalCourse(ccId, ccId, ccId);
		
		String coId = "IndecPerf CO";
		cmAdmin.createCourseOffering(coId, csId, csId, "open", asId, ccId, null, null);
		
		for(int i = 1; i <= secCount; i++) {
			String esId = esPrefix + i;
			Set<String> instructors = new HashSet<String>();
			instructors.add("instructor_A_" + i);
			instructors.add("instructor_B_" + i);
			instructors.add("instructor_C_" + i);
			cmAdmin.createEnrollmentSet(esId, esId, esId, "lecture", "3", coId, instructors);
		}
		
		for(int i = 1; i <= secCount; i++) {
			String secId = secPrefix + i;
			cmAdmin.createSection(secId, secId, secId, "lecture", null, coId, (esPrefix + i));
		}
		
		for(int i = 1; i <= secCount; i++) {
			for(int j = 1; j <= enrollmentsPerEnrollmentSet; j++) {
				cmAdmin.addOrUpdateEnrollment("student" + j, esPrefix + i, "enrolled", "3", "letter grade");
			}
		}

		for(int i = 1; i <= secCount; i++) {
			for(int j = 1; j <= membersPerSection; j++) {
				cmAdmin.addOrUpdateSectionMembership("student" + j, "some role", secPrefix + i, "some status");
			}
		}
	} catch (Exception e) {
		tm.rollback(status);
	} finally {
		if(!status.isCompleted()) {
			tm.commit(status);
		}
	}
}
 
Example 18
Source File: PersistHelper.java    From bulbasaur with Apache License 2.0 4 votes vote down vote up
private TransactionStatus getTransactionStatus() {
	DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
	definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
	definition.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
	return transactionManager.getTransaction(definition);
}
 
Example 19
Source File: SpringTransactionManager.java    From dalesbred with MIT License 4 votes vote down vote up
private static @NotNull DefaultTransactionDefinition settingsToSpringDefinition(@NotNull TransactionSettings settings) {
    DefaultTransactionDefinition df = new DefaultTransactionDefinition();
    df.setIsolationLevel(springIsolationCode(settings.getIsolation()));
    df.setPropagationBehavior(springPropagationCode(settings.getPropagation()));
    return df;
}
 
Example 20
Source File: DeploymentHelper.java    From hawkbit with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Executes the modifying action in new transaction
 *
 * @param txManager
 *            transaction manager interface
 * @param transactionName
 *            the name of the new transaction
 * @param isolationLevel
 *            isolation level of the new transaction
 * @param action
 *            the callback to execute in new tranaction
 *
 * @return the result of the action
 */
public static <T> T runInNewTransaction(@NotNull final PlatformTransactionManager txManager,
        final String transactionName, final int isolationLevel, @NotNull final TransactionCallback<T> action) {
    final DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName(transactionName);
    def.setReadOnly(false);
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    def.setIsolationLevel(isolationLevel);
    return new TransactionTemplate(txManager, def).execute(action);
}