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; } }
/** * 补偿的时候,不走分布式事务处理 * * @param point point 切点 * @param info 信息 * @return Object * @throws Throwable */ @Override public Object handler(ProceedingJoinPoint point, TxTransactionInfo info) throws Throwable { TxTransactionLocal.getInstance().setTxGroupId(CommonConstant.COMPENSATE_ID); DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); TransactionStatus transactionStatus = platformTransactionManager.getTransaction(def); try { final Object proceed = point.proceed(); platformTransactionManager.commit(transactionStatus); LogUtil.info(LOGGER, "补偿事务执行成功!事务组id为:{}", info::getTxGroupId); return proceed; } catch (Throwable e) { LogUtil.info(LOGGER, "补偿事务执行失败!事务组id为:{}", info::getTxGroupId); platformTransactionManager.rollback(transactionStatus); throw e; } finally { TxTransactionLocal.getInstance().removeTxGroupId(); CompensationLocal.getInstance().removeCompensationId(); } }
@Override public EasyTransResult invoke(EasyTransFilterChain filterChain, Map<String, Object> header, EasyTransRequest<?, ?> request) { Integer pTrxStatus = MetaDataFilter.getMetaData(EasytransConstant.CallHeadKeys.PARENT_TRANSACTION_STATUS); if(!pTrxStatus.equals(com.yiqiniu.easytrans.datasource.TransStatusLogger.TransactionStatus.UNKNOWN)){ // start transaction to update PlatformTransactionManager transactionManager = getTransactionManager(filterChain, request); TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager, new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED)); TransactionId pTrxId = MetaDataFilter.getMetaData(EasytransConstant.CallHeadKeys.PARENT_TRX_ID_KEY); transactionTemplate.execute(new TransactionCallback<Object>() { @Override public Object doInTransaction(TransactionStatus status) { TransactionId trxId = pTrxId; transStatusLogger.updateExecuteFlagForSlaveTrx(trxId, request, pTrxStatus); return null; } }); boolean commited = pTrxStatus.equals(com.yiqiniu.easytrans.datasource.TransStatusLogger.TransactionStatus.COMMITTED); //may be concurrent,but it's ok easyTransSynchronizer.cascadeExecuteCachedTransaction(pTrxId, commited); } return filterChain.invokeFilterChain(header, request); }
/** * 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); } }
public Object execGroovyRetObjByDbTranNest(String groovyName, String methodName, Integer nestDef, 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); if(nestDef==null){ nestDef=TransactionDefinition.PROPAGATION_REQUIRED; } def.setPropagationBehavior(nestDef); 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; } }
@Override public boolean addBook(Book book) { // TODO Auto-generated method stub TransactionDefinition definition = new DefaultTransactionDefinition(); TransactionStatus transactionStatus = transactionManager.getTransaction(definition); if (searchBook(book.getISBN()).getISBN() == 98564567l) { System.out.println("no book"); int rows = bookDAO.addBook(book); if (rows > 0) { transactionManager.commit(transactionStatus); return true; } } return false; }
@Override public boolean deleteBook(long ISBN) { // TODO Auto-generated method stub TransactionDefinition definition = new DefaultTransactionDefinition(); TransactionStatus transactionStatus = transactionManager.getTransaction(definition); if (searchBook(ISBN).getISBN() != 98564567l) { boolean deleted = bookDAO.deleteBook(ISBN); if (deleted) { transactionManager.commit(transactionStatus); return true; } } return false; }
@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 } }
@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"); } }
@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(); }
@Test public void jtaTransactionManagerWithDoubleRollback() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE); JtaTransactionManager ptm = newJtaTransactionManager(ut); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); TransactionStatus status = ptm.getTransaction(new DefaultTransactionDefinition()); assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); // first rollback ptm.rollback(status); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); try { // second rollback attempt ptm.rollback(status); fail("Should have thrown IllegalTransactionStateException"); } catch (IllegalTransactionStateException ex) { // expected } verify(ut).begin(); verify(ut).rollback(); }
@Test public void jtaTransactionManagerWithRollbackAndCommit() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE); JtaTransactionManager ptm = newJtaTransactionManager(ut); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); TransactionStatus status = ptm.getTransaction(new DefaultTransactionDefinition()); assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); // first: rollback ptm.rollback(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).rollback(); }
@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()); }
@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 } }
@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 } }
@Test public void propagationNestedFailsInCaseOfExistingTransaction() { MockUOWManager manager = new MockUOWManager(); manager.setUOWStatus(UOWManager.UOW_STATUS_ACTIVE); WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager); DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED); try { ptm.execute(definition, new TransactionCallback<String>() { @Override public String doInTransaction(TransactionStatus status) { return "result"; } }); fail("Should have thrown NestedTransactionNotSupportedException"); } catch (NestedTransactionNotSupportedException ex) { // expected } }
@Test public void testTransactionCommit() 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.commit(ts); verify(session).commit(); verify(session).close(); verify(con).close(); }
@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(); }
public TransactionImpl(PlatformTransactionManager transactionManager, PersistenceImpl persistence, boolean join, @Nullable TransactionParams params, String storeName) { this.tm = transactionManager; this.persistence = persistence; this.storeName = storeName; 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); }
/** * @return List of next entities for this connection or none if there are no one left. * @throws Exception * Exception. * */ public Collection<T> getNextEntities() throws Exception { if (externalHighestCommittedUSN <= internalHighestCommittedUSN) { return null; } LdapSearchBaseDefinition searchBase = getSearchBaseDefinitions().get( currentSearchBaseIndex); Collection<T> entities = null; while ((entities = getNextEntities(searchBase)) == null || entities.size() == 0) { currentSearchBaseIndex++; if (currentSearchBaseIndex >= getSearchBaseDefinitions().size()) { return null; } transactionDefinition = new DefaultTransactionDefinition( TransactionDefinition.PROPAGATION_REQUIRED); pagedResultsControl = new PagedResultsDirContextProcessor(pagingSize); noEntitiesLeft = false; searchBase = getSearchBaseDefinitions().get(currentSearchBaseIndex); } return entities; }
public void test_basics() { BoneCPDataSource ds = new BoneCPDataSource(); HSQLDbDialect dialect = HSQLDbDialect.INSTANCE; NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(ds); DefaultTransactionDefinition transDefn = new DefaultTransactionDefinition(); DataSourceTransactionManager transMgr = new DataSourceTransactionManager(); TransactionTemplate transTemplate = new TransactionTemplate(transMgr, transDefn); DbConnector test = new DbConnector("Test", dialect, ds, jdbcTemplate, null, transTemplate); assertSame(ds, test.getDataSource()); assertSame(dialect, test.getDialect()); assertSame(jdbcTemplate, test.getJdbcTemplate()); assertSame(jdbcTemplate.getJdbcOperations(), test.getJdbcOperations()); assertEquals(null, test.getHibernateSessionFactory()); assertEquals(null, test.getHibernateTemplate()); assertSame(transMgr, test.getTransactionManager()); assertSame(transTemplate, test.getTransactionTemplate()); test.close(); }
@Test(expected = TransientDataAccessResourceException.class) public void testNonSpringTxFactoryWithTx() throws Exception { Environment original = sqlSessionFactory.getConfiguration().getEnvironment(); Environment nonSpring = new Environment("non-spring", new JdbcTransactionFactory(), dataSource,null); sqlSessionFactory.getConfiguration().setEnvironment(nonSpring); TransactionStatus status = null; try { status = txManager.getTransaction(new DefaultTransactionDefinition()); session = SqlSessionUtils.getSqlSession(sqlSessionFactory); fail("should not be able to get an SqlSession using non-Spring tx manager when there is an active Spring tx"); } finally { // rollback required to close connection txManager.rollback(status); sqlSessionFactory.getConfiguration().setEnvironment(original); } }
@Test(expected = TransientDataAccessResourceException.class) public void testChangeExecutorTypeInTx() throws Exception { TransactionStatus status = null; try { status = txManager.getTransaction(new DefaultTransactionDefinition()); session = SqlSessionUtils.getSqlSession(sqlSessionFactory); session = SqlSessionUtils.getSqlSession(sqlSessionFactory, ExecutorType.BATCH, exceptionTranslator); fail("should not be able to change the Executor type during an existing transaction"); } finally { SqlSessionUtils.closeSqlSession(session, sqlSessionFactory); // rollback required to close connection txManager.rollback(status); } }
@Test public void testWithJtaTxManager() { JtaTransactionManager jtaManager = new JtaTransactionManager(new MockUserTransaction()); DefaultTransactionDefinition txDef = new DefaultTransactionDefinition(); txDef.setPropagationBehaviorName("PROPAGATION_REQUIRED"); TransactionStatus status = jtaManager.getTransaction(txDef); session = SqlSessionUtils.getSqlSession(sqlSessionFactory); session.getMapper(TestMapper.class).findTest(); SqlSessionUtils.closeSqlSession(session, sqlSessionFactory); jtaManager.commit(status); // assume a real JTA tx would enlist and commit the JDBC connection assertNoCommitJdbc(); assertCommitSession(); assertSingleConnection(); }
@Test public void testWithTxSupports() { DefaultTransactionDefinition txDef = new DefaultTransactionDefinition(); txDef.setPropagationBehaviorName("PROPAGATION_SUPPORTS"); TransactionStatus status = txManager.getTransaction(txDef); session = SqlSessionUtils.getSqlSession(sqlSessionFactory); session.getMapper(TestMapper.class).findTest(); SqlSessionUtils.closeSqlSession(session, sqlSessionFactory); txManager.commit(status); // SUPPORTS should just activate tx synchronization but not commits assertNoCommit(); assertSingleConnection(); }
@Test public void testRollbackWithTxSupports() { DefaultTransactionDefinition txDef = new DefaultTransactionDefinition(); txDef.setPropagationBehaviorName("PROPAGATION_SUPPORTS"); TransactionStatus status = txManager.getTransaction(txDef); session = SqlSessionUtils.getSqlSession(sqlSessionFactory); session.getMapper(TestMapper.class).findTest(); SqlSessionUtils.closeSqlSession(session, sqlSessionFactory); txManager.rollback(status); // SUPPORTS should just activate tx synchronization but not commits assertNoCommit(); assertSingleConnection(); }
@Test public void testWithTxRequired() { DefaultTransactionDefinition txDef = new DefaultTransactionDefinition(); txDef.setPropagationBehaviorName("PROPAGATION_REQUIRED"); TransactionStatus status = txManager.getTransaction(txDef); session = SqlSessionUtils.getSqlSession(sqlSessionFactory); session.getMapper(TestMapper.class).findTest(); SqlSessionUtils.closeSqlSession(session, sqlSessionFactory); txManager.commit(status); assertCommit(); assertCommitSession(); assertSingleConnection(); }
@Test public void testSqlSessionCommitWithTx() { DefaultTransactionDefinition txDef = new DefaultTransactionDefinition(); txDef.setPropagationBehaviorName("PROPAGATION_REQUIRED"); TransactionStatus status = txManager.getTransaction(txDef); session = SqlSessionUtils.getSqlSession(sqlSessionFactory); session.getMapper(TestMapper.class).findTest(); // commit should no-op since there is an active transaction session.commit(true); SqlSessionUtils.closeSqlSession(session, sqlSessionFactory); txManager.commit(status); // Connection should be committed once, but we explicitly called commit on the SqlSession, // so it should be committed twice assertEquals("should call commit on Connection", 1, connection.getNumberCommits()); assertEquals("should not call rollback on Connection", 0, connection.getNumberRollbacks()); assertEquals("should call commit on SqlSession", 2, executorInterceptor.getCommitCount()); assertEquals("should not call rollback on SqlSession", 0, executorInterceptor.getRollbackCount()); assertSingleConnection(); }
@Test public void testBatchInTx() { setupBatchStatements(); DefaultTransactionDefinition txDef = new DefaultTransactionDefinition(); txDef.setPropagationBehaviorName("PROPAGATION_REQUIRED"); TransactionStatus status = txManager.getTransaction(txDef); session = SqlSessionUtils.getSqlSession(sqlSessionFactory, ExecutorType.BATCH, exceptionTranslator); session.getMapper(TestMapper.class).insertTest("test1"); session.getMapper(TestMapper.class).insertTest("test2"); session.getMapper(TestMapper.class).insertTest("test3"); SqlSessionUtils.closeSqlSession(session, sqlSessionFactory); txManager.commit(status); assertCommit(); assertSingleConnection(); assertExecuteCount(3); }
@Test(expected = DataAccessException.class) public void testBatchInTxWithError() { setupBatchStatements(); DefaultTransactionDefinition txDef = new DefaultTransactionDefinition(); txDef.setPropagationBehaviorName("PROPAGATION_REQUIRED"); TransactionStatus status = txManager.getTransaction(txDef); session = SqlSessionUtils.getSqlSession(sqlSessionFactory, ExecutorType.BATCH, exceptionTranslator); session.getMapper(TestMapper.class).insertTest("test1"); session.getMapper(TestMapper.class).insertTest("test2"); session.update("org.mybatis.spring.TestMapper.insertFail"); session.getMapper(TestMapper.class).insertTest("test3"); SqlSessionUtils.closeSqlSession(session, sqlSessionFactory); txManager.commit(status); }
@Test public void shouldNoOpWithTx() throws Exception { DefaultTransactionDefinition txDef = new DefaultTransactionDefinition(); txDef.setPropagationBehaviorName("PROPAGATION_REQUIRED"); TransactionStatus status = txManager.getTransaction(txDef); SpringManagedTransactionFactory transactionFactory = new SpringManagedTransactionFactory(); SpringManagedTransaction transaction = (SpringManagedTransaction) transactionFactory.newTransaction(dataSource, null, false); transaction.getConnection(); transaction.commit(); transaction.close(); assertEquals("should not call commit on Connection", 0, connection.getNumberCommits()); assertFalse("should not close the Connection", connection.isClosed()); txManager.commit(status); }
@Test(expected = TransientDataAccessResourceException.class) public void testNonSpringTxMgrWithTx() throws Exception { Environment original = sqlSessionFactory.getConfiguration().getEnvironment(); Environment nonSpring = new Environment("non-spring", new JdbcTransactionFactory(), dataSource,null); sqlSessionFactory.getConfiguration().setEnvironment(nonSpring); TransactionStatus status = null; try { status = txManager.getTransaction(new DefaultTransactionDefinition()); find(); fail("should not be able to get an SqlSession using non-Spring tx manager when there is an active Spring tx"); } finally { // rollback required to close connection txManager.rollback(status); sqlSessionFactory.getConfiguration().setEnvironment(original); } }
@Test public void testGetConnectionInTx() throws java.sql.SQLException { TransactionStatus status = null; try { status = txManager.getTransaction(new DefaultTransactionDefinition()); java.sql.Connection con = sqlSessionTemplate.getConnection(); assertFalse(con.isClosed()); } finally { // rollback required to close connection txManager.rollback(status); } }
@Test public void testExecutorType() { SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory, ExecutorType.BATCH); assertEquals(ExecutorType.BATCH, template.getExecutorType()); DataSourceTransactionManager manager = new DataSourceTransactionManager(dataSource); TransactionStatus status = null; try { status = manager.getTransaction(new DefaultTransactionDefinition()); // will synchronize the template with the current tx template.getConnection(); SqlSessionHolder holder = (SqlSessionHolder) TransactionSynchronizationManager .getResource(sqlSessionFactory); assertEquals(ExecutorType.BATCH, holder.getExecutorType()); } finally { // rollback required to close connection txManager.rollback(status); } }
public void flush(StatsUsageType statsUsageType) { if (!disabled){ statsUsageDao.flushAndClear(); StatsUsage statsUsage = statsUsageDao.getByUsageType(statsUsageType); if (statsUsage==null){ statsUsage= initCounter(statsUsageType); } TransactionStatus txStatus = null; DefaultTransactionDefinition txDefinition = new DefaultTransactionDefinition(); txDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txDefinition.setReadOnly(false); txStatus = transactionManager.getTransaction(txDefinition); statsUsage.setUsage(counterMap.get(statsUsageType.toString())); statsUsageDao.save(statsUsage); transactionManager.commit(txStatus); } }
/** * @param task * Set the method to run in a transaction * @return the object returned by the callable method * @throws Exception * if there is a problem running the method */ protected final Object doInTransaction(final Callable task) throws Exception { DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition(); transactionDefinition.setName("test"); transactionDefinition .setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus status = transactionManager .getTransaction(transactionDefinition); Object value = null; try { value = task.call(); } catch (Exception ex) { transactionManager.rollback(status); throw ex; } transactionManager.commit(status); return value; }
/** * traction RollBack * * @author zhuoxue * @since 5.0.1 */ @Test public void tractionRollBackTest() { JdbcTemplate andorJT = new JdbcTemplate(tddlDatasource); DefaultTransactionDefinition def = new DefaultTransactionDefinition(); DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(tddlDatasource); 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()); }