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; } }
public AbstractDbDialect(final JdbcTemplate jdbcTemplate, LobHandler lobHandler){ this.jdbcTemplate = jdbcTemplate; this.lobHandler = lobHandler; // 初始化transction this.transactionTemplate = new TransactionTemplate(); transactionTemplate.setTransactionManager(new DataSourceTransactionManager(jdbcTemplate.getDataSource())); transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // 初始化一些数据 jdbcTemplate.execute(new ConnectionCallback() { public Object doInConnection(Connection c) throws SQLException, DataAccessException { DatabaseMetaData meta = c.getMetaData(); databaseName = meta.getDatabaseProductName(); databaseMajorVersion = meta.getDatabaseMajorVersion(); databaseMinorVersion = meta.getDatabaseMinorVersion(); return null; } }); initTables(jdbcTemplate); }
/** * 补偿的时候,不走分布式事务处理 * * @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); }
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 TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException { Transaction.IsolationLevel isolationLevel = translateIsolationLevel(definition.getIsolationLevel()); Transaction t; if (isolationLevel == null) { t = sql.transaction(); } else { t = sql.transaction(isolationLevel); } if (definition.isReadOnly()) { Wrap.execute(() -> t.getConnection().setReadOnly(true)); } return new SqlStreamTransactionStatus(t); }
@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; }
/** * 根据Spring配置的事务设置,为当前线程选择主库还是从库数据源 */ @Override protected void doBegin(Object transaction, TransactionDefinition definition) { if(definition.isReadOnly()) { if(log.isDebugEnabled()) { log.debug("DataSourceTransactionManager set slave"); } DataSourceHolder.setSlave(); } else { if(log.isDebugEnabled()) { log.debug("DataSourceTransactionManager set master"); } DataSourceHolder.setMaster(); } super.doBegin(transaction, definition); }
@Override public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition) throws PersistenceException, SQLException, TransactionException { OpenJPAEntityManager openJpaEntityManager = getOpenJPAEntityManager(entityManager); if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) { // Pass custom isolation level on to OpenJPA's JDBCFetchPlan configuration FetchPlan fetchPlan = openJpaEntityManager.getFetchPlan(); if (fetchPlan instanceof JDBCFetchPlan) { IsolationLevel isolation = IsolationLevel.fromConnectionConstant(definition.getIsolationLevel()); ((JDBCFetchPlan) fetchPlan).setIsolation(isolation); } } entityManager.getTransaction().begin(); if (!definition.isReadOnly()) { // Like with EclipseLink, make sure to start the logic transaction early so that other // participants using the connection (such as JdbcTemplate) run in a transaction. openJpaEntityManager.beginStore(); } // Custom implementation for OpenJPA savepoint handling return new OpenJpaTransactionData(openJpaEntityManager); }
@Test public void testTransactionCommitWithSharedEntityManagerAndPropagationSupports() { given(manager.isOpen()).willReturn(true); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { bean.sharedEntityManager.clear(); return null; } }); verify(manager).clear(); verify(manager).close(); }
@Test public void testTransactionCommitWithExtendedEntityManagerAndPropagationSupports() { given(manager.isOpen()).willReturn(true); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { bean.extendedEntityManager.flush(); return null; } }); verify(manager).flush(); }
@Test public void testTransactionCommitWithPropagationSupports() { given(pmf.getPersistenceManager()).willReturn(pm); PlatformTransactionManager tm = new JdoTransactionManager(pmf); TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); final List l = new ArrayList(); l.add("test"); assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf)); Object result = tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf)); assertTrue("Is not new transaction", !status.isNewTransaction()); PersistenceManagerFactoryUtils.getPersistenceManager(pmf, true); return l; } }); assertTrue("Correct result list", result == l); assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf)); verify(pm, times(2)).close(); }
@Test public void testIsolationLevel() { given(pmf.getPersistenceManager()).willReturn(pm); given(pm.currentTransaction()).willReturn(tx); PlatformTransactionManager tm = new JdoTransactionManager(pmf); TransactionTemplate tt = new TransactionTemplate(tm); tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { } }); verify(tx).setIsolationLevel(Constants.TX_SERIALIZABLE); verify(pm).close(); }
@Override public void startTransaction() { TransactionDefinition defn; boolean doCommit = true; if (transactions.isEmpty()) { log.debug("startTransaction: default"); defn = defaultTxnDef; } else if (writeTxnManager.isNestedTransactionAllowed()) { log.debug("startTransaction: nested"); defn = nested; } else { throw new RuntimeException("nested transactions not supported by current configuration"); } Txn txn = new Txn(writeTxnManager.getTransaction(defn), doCommit); transactions.push(txn); log.debug("startTransaction: " + transactions.size()); }
@Test public void testValidPropagationCodeAndIsolationCodeAndRollbackRules1() { TransactionAttributeEditor pe = new TransactionAttributeEditor(); pe.setAsText("PROPAGATION_MANDATORY,ISOLATION_REPEATABLE_READ,timeout_10,-IOException,+MyRuntimeException"); TransactionAttribute ta = (TransactionAttribute) pe.getValue(); assertNotNull(ta); assertEquals(ta.getPropagationBehavior(), TransactionDefinition.PROPAGATION_MANDATORY); assertEquals(ta.getIsolationLevel(), TransactionDefinition.ISOLATION_REPEATABLE_READ); assertEquals(ta.getTimeout(), 10); assertFalse(ta.isReadOnly()); assertTrue(ta.rollbackOn(new RuntimeException())); assertFalse(ta.rollbackOn(new Exception())); // Check for our bizarre customized rollback rules assertTrue(ta.rollbackOn(new IOException())); assertTrue(!ta.rollbackOn(new MyRuntimeException(""))); }
@Test public void testValidPropagationCodeAndIsolationCodeAndRollbackRules2() { TransactionAttributeEditor pe = new TransactionAttributeEditor(); pe.setAsText("+IOException,readOnly,ISOLATION_READ_COMMITTED,-MyRuntimeException,PROPAGATION_SUPPORTS"); TransactionAttribute ta = (TransactionAttribute) pe.getValue(); assertNotNull(ta); assertEquals(ta.getPropagationBehavior(), TransactionDefinition.PROPAGATION_SUPPORTS); assertEquals(ta.getIsolationLevel(), TransactionDefinition.ISOLATION_READ_COMMITTED); assertEquals(ta.getTimeout(), TransactionDefinition.TIMEOUT_DEFAULT); assertTrue(ta.isReadOnly()); assertTrue(ta.rollbackOn(new RuntimeException())); assertFalse(ta.rollbackOn(new Exception())); // Check for our bizarre customized rollback rules assertFalse(ta.rollbackOn(new IOException())); assertTrue(ta.rollbackOn(new MyRuntimeException(""))); }
@Test public void testDefaultTransactionAttributeToString() { DefaultTransactionAttribute source = new DefaultTransactionAttribute(); source.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); source.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); source.setTimeout(10); source.setReadOnly(true); TransactionAttributeEditor pe = new TransactionAttributeEditor(); pe.setAsText(source.toString()); TransactionAttribute ta = (TransactionAttribute) pe.getValue(); assertEquals(ta, source); assertEquals(ta.getPropagationBehavior(), TransactionDefinition.PROPAGATION_SUPPORTS); assertEquals(ta.getIsolationLevel(), TransactionDefinition.ISOLATION_REPEATABLE_READ); assertEquals(ta.getTimeout(), 10); assertTrue(ta.isReadOnly()); assertTrue(ta.rollbackOn(new RuntimeException())); assertFalse(ta.rollbackOn(new Exception())); source.setTimeout(9); assertNotSame(ta, source); source.setTimeout(10); assertEquals(ta, source); }
@Test public void matchesSpecific() throws Exception { editor.setAsText( "java.lang.Object.hashCode=PROPAGATION_REQUIRED\n" + "java.lang.Object.equals=PROPAGATION_MANDATORY\n" + "java.lang.Object.*it=PROPAGATION_SUPPORTS\n" + "java.lang.Object.notify=PROPAGATION_SUPPORTS\n" + "java.lang.Object.not*=PROPAGATION_REQUIRED"); TransactionAttributeSource tas = (TransactionAttributeSource) editor.getValue(); checkTransactionProperties(tas, Object.class.getMethod("hashCode", (Class[]) null), TransactionDefinition.PROPAGATION_REQUIRED); checkTransactionProperties(tas, Object.class.getMethod("equals", new Class[] { Object.class }), TransactionDefinition.PROPAGATION_MANDATORY); checkTransactionProperties(tas, Object.class.getMethod("wait", (Class[]) null), TransactionDefinition.PROPAGATION_SUPPORTS); checkTransactionProperties(tas, Object.class.getMethod("wait", new Class[] { long.class }), TransactionDefinition.PROPAGATION_SUPPORTS); checkTransactionProperties(tas, Object.class.getMethod("wait", new Class[] { long.class, int.class }), TransactionDefinition.PROPAGATION_SUPPORTS); checkTransactionProperties(tas, Object.class.getMethod("notify", (Class[]) null), TransactionDefinition.PROPAGATION_SUPPORTS); checkTransactionProperties(tas, Object.class.getMethod("notifyAll", (Class[]) null), TransactionDefinition.PROPAGATION_REQUIRED); checkTransactionProperties(tas, Object.class.getMethod("toString", (Class[]) null), -1); }
@Test public void matchesAll() throws Exception { editor.setAsText("java.lang.Object.*=PROPAGATION_REQUIRED"); TransactionAttributeSource tas = (TransactionAttributeSource) editor.getValue(); checkTransactionProperties(tas, Object.class.getMethod("hashCode", (Class[]) null), TransactionDefinition.PROPAGATION_REQUIRED); checkTransactionProperties(tas, Object.class.getMethod("equals", new Class[] { Object.class }), TransactionDefinition.PROPAGATION_REQUIRED); checkTransactionProperties(tas, Object.class.getMethod("wait", (Class[]) null), TransactionDefinition.PROPAGATION_REQUIRED); checkTransactionProperties(tas, Object.class.getMethod("wait", new Class[] { long.class }), TransactionDefinition.PROPAGATION_REQUIRED); checkTransactionProperties(tas, Object.class.getMethod("wait", new Class[] { long.class, int.class }), TransactionDefinition.PROPAGATION_REQUIRED); checkTransactionProperties(tas, Object.class.getMethod("notify", (Class[]) null), TransactionDefinition.PROPAGATION_REQUIRED); checkTransactionProperties(tas, Object.class.getMethod("notifyAll", (Class[]) null), TransactionDefinition.PROPAGATION_REQUIRED); checkTransactionProperties(tas, Object.class.getMethod("toString", (Class[]) null), TransactionDefinition.PROPAGATION_REQUIRED); }
@Test public void testTransactionWithPropagationNested() throws Exception { final TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED); assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive()); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException { assertTrue("Is new transaction", status.isNewTransaction()); } }); assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); verify(con).commit(); verify(con).close(); }
@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 } }
@Override public Object beginTransaction(final EntityManager entityManager, final TransactionDefinition definition) throws SQLException { final boolean readOnly = definition.isReadOnly(); final Connection connection = this.getJdbcConnection(entityManager, readOnly).getConnection(); final Deque<ConnectionContext> deque = curContext.get(); final ConnectionContext context = new ConnectionContext(connection, definition); deque.addLast(context); if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) { getSession(entityManager).getTransaction().setTimeout(definition.getTimeout()); } entityManager.getTransaction().begin(); return prepareTransaction(entityManager, readOnly, definition.getName()); }
/** * @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; }
@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 } }
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); }
@Override public void doBegin(Object transaction, final TransactionDefinition definition) { logger.info("MultiTenantJpaTransactionManager.doBegin()"); super.doBegin(transaction, definition); EntityManagerHolder entityManagerHolder = (EntityManagerHolder) TransactionSynchronizationManager.getResource(getEntityManagerFactory()); EntityManager entityManager = entityManagerHolder.getEntityManager(); String currentTenant = tenantResolver.getCurrentTenant(); logger.info("MultiTenantJpaTransactionManager.doBegin() - currentTenant: " + currentTenant); String currentTenantSet = (String) entityManager.getProperties().get(MULTITENANT_PROPERTY_DEFAULT); logger.info("MultiTenantJpaTransactionManager.doBegin() - currentTenantSet: " + currentTenantSet); if(currentTenantSet != null && !currentTenantSet.equals(currentTenant)) { throw new IllegalStateException("Resource conflict - The EntityManager is already assigned to tenant : " + currentTenant); } entityManager.setProperty(MULTITENANT_PROPERTY_DEFAULT, currentTenant); }
/** * 处理补偿内嵌的远程方法的时候,不提交,只调用 * * @param point point 切点 * @param info 信息 * @return Object * @throws Throwable 异常 */ @Override public Object handler(ProceedingJoinPoint point, TxTransactionInfo info) throws Throwable { DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus transactionStatus = platformTransactionManager.getTransaction(def); try { return point.proceed(); } finally { platformTransactionManager.rollback(transactionStatus); } }
public DataBaseTransactionLogWritterImpl(ObjectSerializer objectSerializer,DataSource dataSource) { super(); this.objectSerializer = objectSerializer; this.dataSource = dataSource; transactionManager = new DataSourceTransactionManager(dataSource); transactionTemplate = new TransactionTemplate(transactionManager, new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW)); }
public int insertUser(final User user) { TransactionDefinition paramTransactionDefinition = new DefaultTransactionDefinition(); TransactionStatus status=platformTransactionManager.getTransaction(paramTransactionDefinition ); String inserQuery = "insert into users (username, password, enabled , id) values (?, ?, ?, ?) "; Object[] params = new Object[]{user.getUserName(), user.getPassword(),user.isEnabled(),user.getId()}; int[] types = new int[]{Types.VARCHAR,Types.VARCHAR,Types.BIT,Types.INTEGER}; int rowsAffected = jdbcTemplate.update(inserQuery,params,types); platformTransactionManager.commit(status); return rowsAffected; }
/** * 支持当前事务;如果不存在创建一个新的 */ private RuleBasedTransactionAttribute requiredTransactionRule () { RuleBasedTransactionAttribute required = new RuleBasedTransactionAttribute(); required.setRollbackRules( Collections.singletonList( new RollbackRuleAttribute( Exception.class ) ) ); required.setPropagationBehavior( TransactionDefinition.PROPAGATION_REQUIRED ); required.setTimeout( TransactionDefinition.TIMEOUT_DEFAULT ); return required; }
/** * 只读事务 */ private RuleBasedTransactionAttribute readOnlyTransactionRule () { RuleBasedTransactionAttribute readOnly = new RuleBasedTransactionAttribute(); readOnly.setReadOnly( true ); readOnly.setPropagationBehavior( TransactionDefinition.PROPAGATION_NOT_SUPPORTED ); return readOnly; }
/** * 事务开始前将数据源手动设置进去 */ @Override protected void doBegin(Object transaction, TransactionDefinition definition) { //若有 @Transaction 注解,并且不是只读,设置为主库 if (!definition.isReadOnly()) { DynamicDataSourceHolder.routeMaster(); } super.doBegin(transaction, definition); }
/** * Vérifie qu'une transaction est ouverte * Correspond au @Transaction(REQUIRED) */ public void assertExistingTransaction() { DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_MANDATORY); // Va envoyer une Exception s'il n'y a pas de Transaction ouverte getTransactionManager().getTransaction(def); }
@Around("@annotation(com.wise.core.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; }
/** * Called during the transaction setup */ protected void onSetUp() throws Exception { super.onSetUp(); System.out.println("java.io.tmpdir == " + System.getProperty("java.io.tmpdir")); // Get the required services this.nodeService = (NodeService) this.applicationContext.getBean("nodeService"); this.contentService = (ContentService) this.applicationContext.getBean("contentService"); this.authenticationService = (MutableAuthenticationService) this.applicationContext .getBean("authenticationService"); this.actionService = (ActionService) this.applicationContext.getBean("actionService"); this.transactionService = (TransactionService) this.applicationContext.getBean("transactionComponent"); this.authenticationComponent = (AuthenticationComponent) this.applicationContext .getBean("authenticationComponent"); this.receiver = (RepoTransferReceiverImpl) this.getApplicationContext().getBean("transferReceiver"); this.policyComponent = (PolicyComponent) this.getApplicationContext().getBean("policyComponent"); this.searchService = (SearchService) this.getApplicationContext().getBean("searchService"); this.repositoryHelper = (Repository) this.getApplicationContext().getBean("repositoryHelper"); this.namespaceService = (NamespaceService) this.getApplicationContext().getBean("namespaceService"); this.dummyContent = "This is some dummy content."; this.dummyContentBytes = dummyContent.getBytes("UTF-8"); setTransactionDefinition(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW)); authenticationComponent.setSystemUserAsCurrentUser(); startNewTransaction(); guestHome = repositoryHelper.getGuestHome(); endTransaction(); }
/** * Called during the transaction setup */ protected void onSetUp() throws Exception { // Catch transactions left dangling by inadequate transaction handling during test failures if (AlfrescoTransactionSupport.getTransactionReadState() != TxnReadState.TXN_NONE) { fail("Dangling transaction at start of test."); } super.onSetUp(); // Get the required services this.transferService = (TransferService)this.applicationContext.getBean("TransferService"); this.contentService = (ContentService)this.applicationContext.getBean("ContentService"); this.transferServiceImpl = (TransferServiceImpl2)this.applicationContext.getBean("transferService2"); this.searchService = (SearchService)this.applicationContext.getBean("SearchService"); this.transactionService = (TransactionService)this.applicationContext.getBean("TransactionService"); this.nodeService = (NodeService) this.applicationContext.getBean("nodeService"); this.contentService = (ContentService) this.applicationContext.getBean("contentService"); this.authenticationService = (MutableAuthenticationService) this.applicationContext.getBean("authenticationService"); this.actionService = (ActionService)this.applicationContext.getBean("actionService"); this.permissionService = (PermissionService)this.applicationContext.getBean("permissionService"); this.receiver = (TransferReceiver)this.applicationContext.getBean("transferReceiver"); this.transferManifestNodeFactory = (TransferManifestNodeFactory)this.applicationContext.getBean("transferManifestNodeFactory"); this.authenticationComponent = (AuthenticationComponent) this.applicationContext.getBean("authenticationComponent"); this.lockService = (LockService) this.applicationContext.getBean("lockService"); this.personService = (PersonService)this.applicationContext.getBean("PersonService"); this.descriptorService = (DescriptorService)this.applicationContext.getBean("DescriptorService"); this.copyService = (CopyService)this.applicationContext.getBean("CopyService"); this.serverDescriptor = descriptorService.getServerDescriptor(); this.repositoryHelper = (Repository) this.applicationContext.getBean("repositoryHelper"); REPO_ID_B = descriptorService.getCurrentRepositoryDescriptor().getId(); authenticationComponent.setSystemUserAsCurrentUser(); setTransactionDefinition(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW)); assertNotNull("receiver is null", this.receiver); }
private UserTransaction getTxn() { return new SpringAwareUserTransaction( transactionManager, false, TransactionDefinition.ISOLATION_DEFAULT, TransactionDefinition.PROPAGATION_REQUIRED, TransactionDefinition.TIMEOUT_DEFAULT); }