org.springframework.transaction.support.DefaultTransactionDefinition Java Examples

The following examples show how to use org.springframework.transaction.support.DefaultTransactionDefinition. 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: JDBCTemplateTest.java    From tddl with Apache License 2.0 8 votes vote down vote up
@Test
public void tractionRollBackTest() {
    JdbcTemplate andorJT = new JdbcTemplate(us);
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(us);
    TransactionStatus ts = transactionManager.getTransaction(def);

    try {
        sql = String.format("insert into %s (pk,name) values(?,?)", normaltblTableName);
        andorJT.update(sql, new Object[] { RANDOM_ID, name });
        sql = String.format("select * from %s where pk= ?", normaltblTableName);
        Map re = andorJT.queryForMap(sql, new Object[] { RANDOM_ID });
        Assert.assertEquals(name, String.valueOf(re.get("NAME")));
        // 回滚
        transactionManager.rollback(ts);
    } catch (DataAccessException ex) {
        transactionManager.rollback(ts);
        throw ex;
    } finally {
    }
    // 验证查询不到数据
    sql = String.format("select * from %s where pk= ?", normaltblTableName);
    List le = andorJT.queryForList(sql, new Object[] { RANDOM_ID });
    Assert.assertEquals(0, le.size());
}
 
Example #2
Source File: IsolationLevelDataSourceRouter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Supports Integer values for the isolation level constants
 * as well as isolation level names as defined on the
 * {@link org.springframework.transaction.TransactionDefinition TransactionDefinition interface}.
 */
@Override
protected Object resolveSpecifiedLookupKey(Object lookupKey) {
	if (lookupKey instanceof Integer) {
		return lookupKey;
	}
	else if (lookupKey instanceof String) {
		String constantName = (String) lookupKey;
		if (!constantName.startsWith(DefaultTransactionDefinition.PREFIX_ISOLATION)) {
			throw new IllegalArgumentException("Only isolation constants allowed");
		}
		return constants.asNumber(constantName);
	}
	else {
		throw new IllegalArgumentException(
				"Invalid lookup key - needs to be isolation level Integer or isolation level name String: " + lookupKey);
	}
}
 
Example #3
Source File: TransactionSupportTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void existingTransaction() {
	PlatformTransactionManager tm = new TestTransactionManager(true, true);
	DefaultTransactionStatus status1 = (DefaultTransactionStatus)
			tm.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_SUPPORTS));
	assertTrue("Must have transaction", status1.getTransaction() != null);
	assertTrue("Must not be new transaction", !status1.isNewTransaction());

	DefaultTransactionStatus status2 = (DefaultTransactionStatus)
			tm.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED));
	assertTrue("Must have transaction", status2.getTransaction() != null);
	assertTrue("Must not be new transaction", !status2.isNewTransaction());

	try {
		DefaultTransactionStatus status3 = (DefaultTransactionStatus)
				tm.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_MANDATORY));
		assertTrue("Must have transaction", status3.getTransaction() != null);
		assertTrue("Must not be new transaction", !status3.isNewTransaction());
	}
	catch (NoTransactionException ex) {
		fail("Should not have thrown NoTransactionException");
	}
}
 
Example #4
Source File: ReactiveTransactionSupportTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void noExistingTransaction() {
	ReactiveTransactionManager tm = new ReactiveTestTransactionManager(false, true);

	tm.getReactiveTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_SUPPORTS))
			.subscriberContext(TransactionContextManager.createTransactionContext()).cast(GenericReactiveTransaction.class)
			.as(StepVerifier::create).consumeNextWith(actual ->
				assertFalse(actual.hasTransaction())
			).verifyComplete();

	tm.getReactiveTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED))
			.cast(GenericReactiveTransaction.class).subscriberContext(TransactionContextManager.createTransactionContext())
			.as(StepVerifier::create).consumeNextWith(actual -> {
				assertTrue(actual.hasTransaction());
				assertTrue(actual.isNewTransaction());
			}).verifyComplete();

	tm.getReactiveTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_MANDATORY))
			.subscriberContext(TransactionContextManager.createTransactionContext()).cast(GenericReactiveTransaction.class)
			.as(StepVerifier::create).expectError(IllegalTransactionStateException.class).verify();
}
 
Example #5
Source File: StartCompensationHandler.java    From Raincat with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 补偿的时候,不走分布式事务处理.
 *
 * @param point point 切点
 * @param info  信息
 * @return Object
 * @throws Throwable ex
 */
@Override
public Object handler(final ProceedingJoinPoint point, final TxTransactionInfo info) throws Throwable {
    TxTransactionLocal.getInstance().setTxGroupId(CommonConstant.COMPENSATE_ID);

    PlatformTransactionManager platformTransactionManager =
            TransactionManagerHelper.getTransactionManager(info.getTransactionManager());
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    TransactionStatus transactionStatus = platformTransactionManager.getTransaction(def);
    try {
        final Object proceed = point.proceed();
        platformTransactionManager.commit(transactionStatus);
        return proceed;
    } catch (Throwable e) {
        platformTransactionManager.rollback(transactionStatus);
        throw e;
    } finally {
        TxTransactionLocal.getInstance().removeTxGroupId();
        CompensationLocal.getInstance().removeCompensationId();
    }
}
 
Example #6
Source File: WebSphereUowTransactionManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void uowManagerFoundInJndi() {
	MockUOWManager manager = new MockUOWManager();
	ExpectedLookupTemplate jndiTemplate =
			new ExpectedLookupTemplate(WebSphereUowTransactionManager.DEFAULT_UOW_MANAGER_NAME, manager);
	WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager();
	ptm.setJndiTemplate(jndiTemplate);
	ptm.afterPropertiesSet();

	DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
	assertEquals("result", ptm.execute(definition, new TransactionCallback<String>() {
		@Override
		public String doInTransaction(TransactionStatus status) {
			return "result";
		}
	}));

	assertEquals(UOWManager.UOW_TYPE_GLOBAL_TRANSACTION, manager.getUOWType());
	assertFalse(manager.getJoined());
	assertFalse(manager.getRollbackOnly());
}
 
Example #7
Source File: JtaTransactionManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithDoubleCommit() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION,
			Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	TransactionStatus status = ptm.getTransaction(new DefaultTransactionDefinition());
	assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
	// first commit
	ptm.commit(status);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	try {
		// second commit attempt
		ptm.commit(status);
		fail("Should have thrown IllegalTransactionStateException");
	}
	catch (IllegalTransactionStateException ex) {
		// expected
	}

	verify(ut).begin();
	verify(ut).commit();
}
 
Example #8
Source File: JtaTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithDoubleCommit() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION,
			Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	TransactionStatus status = ptm.getTransaction(new DefaultTransactionDefinition());
	assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
	// first commit
	ptm.commit(status);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	try {
		// second commit attempt
		ptm.commit(status);
		fail("Should have thrown IllegalTransactionStateException");
	}
	catch (IllegalTransactionStateException ex) {
		// expected
	}

	verify(ut).begin();
	verify(ut).commit();
}
 
Example #9
Source File: WaitingQueueSubscriptionProcessor.java    From alf.io with GNU General Public License v3.0 6 votes vote down vote up
public void handleWaitingTickets() {
    Map<Boolean, List<Event>> activeEvents = eventManager.getActiveEvents().stream()
        .collect(Collectors.partitioningBy(this::isWaitingListFormEnabled));
    activeEvents.get(true).forEach(event -> {
        TransactionStatus transaction = transactionManager.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW));
        try {
            ticketReservationManager.revertTicketsToFreeIfAccessRestricted(event.getId());
            revertTicketToFreeIfCategoryIsExpired(event);
            distributeAvailableSeats(event);
            transactionManager.commit(transaction);
        } catch(Exception ex) {
            if(!(ex instanceof TransactionException)) {
                transactionManager.rollback(transaction);
            }
            log.error("cannot process waiting list for event {}", event.getShortName(), ex);
        }
    });
    activeEvents.get(false).forEach(eventManager::resetReleasedTickets);
}
 
Example #10
Source File: SpringHibernateTransactionOperations.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 JpaTransactionStatus(status));
                } catch (RuntimeException | Error ex) {
                    throw ex;
                } catch (Exception e) {
                    throw new UndeclaredThrowableException(e, "TransactionCallback threw undeclared checked exception");
                }
            }
    );
}
 
Example #11
Source File: IsolationLevelDataSourceRouter.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Supports Integer values for the isolation level constants
 * as well as isolation level names as defined on the
 * {@link org.springframework.transaction.TransactionDefinition TransactionDefinition interface}.
 */
@Override
protected Object resolveSpecifiedLookupKey(Object lookupKey) {
	if (lookupKey instanceof Integer) {
		return lookupKey;
	}
	else if (lookupKey instanceof String) {
		String constantName = (String) lookupKey;
		if (!constantName.startsWith(DefaultTransactionDefinition.PREFIX_ISOLATION)) {
			throw new IllegalArgumentException("Only isolation constants allowed");
		}
		return constants.asNumber(constantName);
	}
	else {
		throw new IllegalArgumentException(
				"Invalid lookup key - needs to be isolation level Integer or isolation level name String: " + lookupKey);
	}
}
 
Example #12
Source File: ReactiveTransactionSupportTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void transactionTemplateWithException() {
	ReactiveTestTransactionManager tm = new ReactiveTestTransactionManager(false, true);
	TransactionalOperator operator = TransactionalOperator.create(tm, new DefaultTransactionDefinition());
	RuntimeException ex = new RuntimeException("Some application exception");

	Mono.error(ex).as(operator::transactional)
			.as(StepVerifier::create)
			.expectError(RuntimeException.class)
			.verify();

	assertHasBegan(tm);
	assertHasNotCommitted(tm);
	assertHasRolledBack(tm);
	assertHasNotSetRollbackOnly(tm);
	assertHasCleanedUp(tm);
}
 
Example #13
Source File: AlarmAdminService.java    From frostmourne with MIT License 6 votes vote down vote up
public boolean delete(Long alarmId) {
    Alarm alarm = alarmMapper.selectByPrimaryKey(alarmId);
    if (alarm == null) {
        return false;
    }
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionStatus status = frostmourneTransactionManager.getTransaction(def);
    try {
        alarmMapper.deleteByPrimaryKey(alarmId);
        alertMapper.deleteByAlarm(alarmId);
        metricMapper.deleteByAlarm(alarmId);
        ruleMapper.deleteByAlarm(alarmId);
        rulePropertyMapper.deleteByAlarm(alarmId);
        recipientMapper.deleteByAlarm(alarmId);
        scheduleService.removeJob(Math.toIntExact(alarm.getJob_id()));
    } catch (Exception ex) {
        frostmourneTransactionManager.rollback(status);
    }
    frostmourneTransactionManager.commit(status);
    return true;
}
 
Example #14
Source File: JmsTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testTransactionRollback() throws JMSException {
	ConnectionFactory cf = mock(ConnectionFactory.class);
	Connection con = mock(Connection.class);
	final Session session = mock(Session.class);

	given(cf.createConnection()).willReturn(con);
	given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session);

	JmsTransactionManager tm = new JmsTransactionManager(cf);
	TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
	JmsTemplate jt = new JmsTemplate(cf);
	jt.execute(new SessionCallback<Void>() {
		@Override
		public Void doInJms(Session sess) {
			assertTrue(sess == session);
			return null;
		}
	});
	tm.rollback(ts);

	verify(session).rollback();
	verify(session).close();
	verify(con).close();
}
 
Example #15
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 #16
Source File: WebSphereUowTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void uowManagerFoundInJndi() {
	MockUOWManager manager = new MockUOWManager();
	ExpectedLookupTemplate jndiTemplate =
			new ExpectedLookupTemplate(WebSphereUowTransactionManager.DEFAULT_UOW_MANAGER_NAME, manager);
	WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager();
	ptm.setJndiTemplate(jndiTemplate);
	ptm.afterPropertiesSet();

	DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
	assertEquals("result", ptm.execute(definition, new TransactionCallback<String>() {
		@Override
		public String doInTransaction(TransactionStatus status) {
			return "result";
		}
	}));

	assertEquals(UOWManager.UOW_TYPE_GLOBAL_TRANSACTION, manager.getUOWType());
	assertFalse(manager.getJoined());
	assertFalse(manager.getRollbackOnly());
}
 
Example #17
Source File: WebSphereUowTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void propagationMandatoryFailsInCaseOfNoExistingTransaction() {
	MockUOWManager manager = new MockUOWManager();
	WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager);
	DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
	definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_MANDATORY);

	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 #18
Source File: JmsTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testLazyTransactionalSession() throws JMSException {
	ConnectionFactory cf = mock(ConnectionFactory.class);
	Connection con = mock(Connection.class);
	final Session session = mock(Session.class);

	JmsTransactionManager tm = new JmsTransactionManager(cf);
	tm.setLazyResourceRetrieval(true);
	TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());

	given(cf.createConnection()).willReturn(con);
	given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session);

	JmsTemplate jt = new JmsTemplate(cf);
	jt.execute((SessionCallback<Void>) sess -> {
		assertSame(sess, session);
		return null;
	});
	tm.commit(ts);

	verify(session).commit();
	verify(session).close();
	verify(con).close();
}
 
Example #19
Source File: TransactionSupportTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void noExistingTransaction() {
	PlatformTransactionManager tm = new TestTransactionManager(false, true);
	DefaultTransactionStatus status1 = (DefaultTransactionStatus)
			tm.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_SUPPORTS));
	assertTrue("Must not have transaction", status1.getTransaction() == null);

	DefaultTransactionStatus status2 = (DefaultTransactionStatus)
			tm.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED));
	assertTrue("Must have transaction", status2.getTransaction() != null);
	assertTrue("Must be new transaction", status2.isNewTransaction());

	try {
		tm.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_MANDATORY));
		fail("Should not have thrown NoTransactionException");
	}
	catch (IllegalTransactionStateException ex) {
		// expected
	}
}
 
Example #20
Source File: DataBaseTransactionLogWritterImpl.java    From EasyTransaction with Apache License 2.0 6 votes vote down vote up
public DataBaseTransactionLogWritterImpl(ObjectSerializer objectSerializer,DataSource dataSource, ByteFormIdCodec idCodec,String tablePrefix) {
	super();
	this.objectSerializer = objectSerializer;
	this.idCodec = idCodec;
	this.dataSource = dataSource;
	transactionManager = new DataSourceTransactionManager(dataSource);
	transactionTemplate = new TransactionTemplate(transactionManager, new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW));
	
	if(!StringUtils.isEmpty(tablePrefix)) {
		tablePrefix = tablePrefix.trim();
		
		cleanLog = cleanLog.replace("trans_log_detail", tablePrefix + "trans_log_detail");
		cleanLog = cleanLog.replace("trans_log_unfinished", tablePrefix + "trans_log_unfinished");
		deleteUnfinishedTag = deleteUnfinishedTag.replace("trans_log_unfinished", tablePrefix + "trans_log_unfinished");
		insertTransDetail = insertTransDetail.replace("trans_log_detail", tablePrefix + "trans_log_detail");
		insertUnfinished = insertUnfinished.replace("trans_log_unfinished", tablePrefix + "trans_log_unfinished");
	}

}
 
Example #21
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 #22
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 #23
Source File: SpringHibernateTransactionOperations.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
/**
 * Default constructor.
 * @param hibernateTransactionManager The hibernate transaction manager.
 */
protected SpringHibernateTransactionOperations(HibernateTransactionManager hibernateTransactionManager) {
    this.sessionFactory = hibernateTransactionManager.getSessionFactory();
    this.transactionManager = hibernateTransactionManager;
    this.writeTransactionTemplate = new TransactionTemplate(hibernateTransactionManager);
    DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
    transactionDefinition.setReadOnly(true);
    this.readTransactionTemplate = new TransactionTemplate(hibernateTransactionManager, transactionDefinition);
}
 
Example #24
Source File: JmsTransactionManagerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testParticipatingTransactionWithRollbackOnly() throws JMSException {
	ConnectionFactory cf = mock(ConnectionFactory.class);
	Connection con = mock(Connection.class);
	final Session session = mock(Session.class);

	given(cf.createConnection()).willReturn(con);
	given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session);

	JmsTransactionManager tm = new JmsTransactionManager(cf);
	TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
	final JmsTemplate jt = new JmsTemplate(cf);
	jt.execute((SessionCallback<Void>) sess -> {
		assertSame(sess, session);
		return null;
	});
	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			jt.execute((SessionCallback<Void>) sess -> {
				assertSame(sess, session);
				return null;
			});
			status.setRollbackOnly();
		}
	});
	try {
		tm.commit(ts);
		fail("Should have thrown UnexpectedRollbackException");
	}
	catch (UnexpectedRollbackException ex) {
		// expected
	}

	verify(session).rollback();
	verify(session).close();
	verify(con).close();
}
 
Example #25
Source File: JmsTransactionManagerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testParticipatingTransactionWithCommit() throws JMSException {
	ConnectionFactory cf = mock(ConnectionFactory.class);
	Connection con = mock(Connection.class);
	final Session session = mock(Session.class);

	given(cf.createConnection()).willReturn(con);
	given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session);

	JmsTransactionManager tm = new JmsTransactionManager(cf);
	TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
	final JmsTemplate jt = new JmsTemplate(cf);
	jt.execute((SessionCallback<Void>) sess -> {
		assertSame(sess, session);
		return null;
	});
	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			jt.execute((SessionCallback<Void>) sess -> {
				assertSame(sess, session);
				return null;
			});
		}
	});
	tm.commit(ts);

	verify(session).commit();
	verify(session).close();
	verify(con).close();
}
 
Example #26
Source File: WebSphereUowTransactionManagerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void existingNonSpringTransaction() {
	MockUOWManager manager = new MockUOWManager();
	manager.setUOWStatus(UOWManager.UOW_STATUS_ACTIVE);
	WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager);
	DefaultTransactionDefinition definition = new DefaultTransactionDefinition();

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

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

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

	assertEquals(0, manager.getUOWTimeout());
	assertEquals(UOWManager.UOW_TYPE_GLOBAL_TRANSACTION, manager.getUOWType());
	assertTrue(manager.getJoined());
	assertFalse(manager.getRollbackOnly());
}
 
Example #27
Source File: AbstractAsgardConsumer.java    From choerodon-starters with Apache License 2.0 5 votes vote down vote up
protected TransactionStatus createTransactionStatus(final PlatformTransactionManager transactionManager,
                                                    final int isolationLevel) {
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    def.setIsolationLevel(isolationLevel);
    return transactionManager.getTransaction(def);
}
 
Example #28
Source File: WebSphereUowTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 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 #29
Source File: DefaultJpaDialectTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testDefaultBeginTransaction() throws Exception {
	TransactionDefinition definition = new DefaultTransactionDefinition();
	EntityManager entityManager = mock(EntityManager.class);
	EntityTransaction entityTx = mock(EntityTransaction.class);

	given(entityManager.getTransaction()).willReturn(entityTx);

	dialect.beginTransaction(entityManager, definition);
}
 
Example #30
Source File: WebSphereUowTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void newTransactionWithRollbackOnly() {
	MockUOWManager manager = new MockUOWManager();
	WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager);
	DefaultTransactionDefinition definition = new DefaultTransactionDefinition();

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

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

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

	assertEquals(0, manager.getUOWTimeout());
	assertEquals(UOWManager.UOW_TYPE_GLOBAL_TRANSACTION, manager.getUOWType());
	assertFalse(manager.getJoined());
	assertTrue(manager.getRollbackOnly());
}