Java Code Examples for org.springframework.transaction.TransactionStatus

The following examples show how to use org.springframework.transaction.TransactionStatus. These examples are extracted from open source projects. 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 Project: spring-analysis-note   Source File: JmsTransactionManagerTests.java    License: MIT License 6 votes vote down vote up
@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((SessionCallback<Void>) sess -> {
		assertSame(sess, session);
		return null;
	});
	tm.commit(ts);

	verify(session).commit();
	verify(session).close();
	verify(con).close();
}
 
Example 2
Source Project: gocd   Source File: UserSqlMapDao.java    License: Apache License 2.0 6 votes vote down vote up
private void changeEnabledStatus(final List<String> usernames, final boolean enabled) {
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCommit() {
                    clearEnabledUserCountFromCache();
                }
            });
            String queryString = String.format("update %s set enabled = :enabled where name in (:userNames)", User.class.getName());
            Query query = sessionFactory.getCurrentSession().createQuery(queryString);
            query.setParameter("enabled", enabled);
            query.setParameterList("userNames", usernames);
            query.executeUpdate();
        }
    });
}
 
Example 3
Source Project: webcurator   Source File: HeatmapDAOImpl.java    License: Apache License 2.0 6 votes vote down vote up
public void saveOrUpdate(final HeatmapConfig config) {
	if (log.isDebugEnabled()) {
		log.debug("Saving " + config.getClass().getName());
	}
	txTemplate.execute(new TransactionCallback() {
		public Object doInTransaction(TransactionStatus ts) {
			try {
				getSession().saveOrUpdate(config);
			} catch (Exception ex) {
				ts.setRollbackOnly();
			}
			return null;
		}
	});

}
 
Example 4
@Test
public void testTransactionWithPropagationNever() throws Exception {
	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NEVER);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));

	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
			assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
			assertTrue("Is not new transaction", !status.isNewTransaction());
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
}
 
Example 5
/**
 * Check that two transactions are created and committed.
 */
@Test
public void twoTransactionsShouldSucceed() throws Exception {
	TransactionAttribute txatt = new DefaultTransactionAttribute();

	MapTransactionAttributeSource tas1 = new MapTransactionAttributeSource();
	tas1.register(getNameMethod, txatt);
	MapTransactionAttributeSource tas2 = new MapTransactionAttributeSource();
	tas2.register(setNameMethod, txatt);

	TransactionStatus status = mock(TransactionStatus.class);
	PlatformTransactionManager ptm = mock(PlatformTransactionManager.class);
	// expect a transaction
	given(ptm.getTransaction(txatt)).willReturn(status);

	TestBean tb = new TestBean();
	ITestBean itb = (ITestBean) advised(tb, ptm, new TransactionAttributeSource[] {tas1, tas2});

	checkTransactionStatus(false);
	itb.getName();
	checkTransactionStatus(false);
	itb.setName("myName");
	checkTransactionStatus(false);

	verify(ptm, times(2)).commit(status);
}
 
Example 6
@Test
public void shouldRegisterSynchronization_andNotCallItOnTransactionFailure() {
    final TransactionSynchronizationManager synchronizationManager = new TransactionSynchronizationManager();

    final TransactionSynchronization synchronization = mock(TransactionSynchronization.class);
    try {
        transactionTemplate.execute(new org.springframework.transaction.support.TransactionCallbackWithoutResult() {
            @Override protected void doInTransactionWithoutResult(TransactionStatus status) {
                synchronizationManager.registerSynchronization(synchronization);
                throw new RuntimeException();
            }
        });
    } catch (Exception e) {
        //ignore
    }
    verify(synchronization, never()).afterCommit();
}
 
Example 7
/**
 * Test behavior if the first operation on a connection (getAutoCommit) throws SQLException.
 */
@Test
public void testTransactionWithExceptionOnBegin() throws Exception {
	willThrow(new SQLException("Cannot begin")).given(con).getAutoCommit();

	TransactionTemplate tt = new TransactionTemplate(tm);
	try {
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				// something transactional
			}
		});
		fail("Should have thrown CannotCreateTransactionException");
	}
	catch (CannotCreateTransactionException ex) {
		// expected
	}

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	verify(con).close();
}
 
Example 8
@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();
}
 
Example 9
/**
 * If a transaction is currently active for the supplied
 * {@linkplain TestContext test context}, this method will end the transaction
 * and run {@link AfterTransaction @AfterTransaction} methods.
 * <p>{@code @AfterTransaction} methods are guaranteed to be invoked even if
 * an error occurs while ending the transaction.
 */
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
	Method testMethod = testContext.getTestMethod();
	Assert.notNull(testMethod, "The test method of the supplied TestContext must not be null");

	TransactionContext txContext = TransactionContextHolder.removeCurrentTransactionContext();
	// If there was (or perhaps still is) a transaction...
	if (txContext != null) {
		TransactionStatus transactionStatus = txContext.getTransactionStatus();
		try {
			// If the transaction is still active...
			if ((transactionStatus != null) && !transactionStatus.isCompleted()) {
				txContext.endTransaction();
			}
		}
		finally {
			runAfterTransactionMethods(testContext);
		}
	}
}
 
Example 10
Source Project: gocd   Source File: TransactionTemplateTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldUnderstand_InTransaction() {
    TransactionTemplate template = new TransactionTemplate(transactionTemplate);

    final boolean[] inTransactionInBody = new boolean[] {false};
    final boolean[] inTransactionInAfterCommit = new boolean[] {true};
    final boolean[] inTransactionInAfterComplete = new boolean[] {true};

    String returnVal = (String) template.execute(new org.springframework.transaction.support.TransactionCallback() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            setTxnBodyActiveFlag(inTransactionInBody, inTransactionInAfterCommit, inTransactionInAfterComplete, 0);
            return "foo";
        }
    });

    assertThat(inTransactionInBody[0], is(true));
    assertThat(inTransactionInAfterCommit[0], is(false));
    assertThat(inTransactionInAfterComplete[0], is(false));
    assertThat(returnVal, is("foo"));
}
 
Example 11
Source Project: sakai   Source File: SampleDataLoader.java    License: 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 12
@Test
public void testInvalidIsolation() {
	tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);

	given(manager.isOpen()).willReturn(true);

	try {
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
			}
		});
		fail("Should have thrown InvalidIsolationLevelException");
	}
	catch (InvalidIsolationLevelException ex) {
		// expected
	}

	verify(manager).close();
}
 
Example 13
Source Project: olat   Source File: MultithreadedDaoTestNgITCaseNew.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void setup() {
    new TransactionTemplate(txManager).execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            daoIdentity.setType(IdentityImpl.class);
            daoSubscriber.setType(Subscriber.class);
            daoPublisher.setType(Publisher.class);
            daoSubscription.setType(Subscription.class);

            createSubscription(createPublisher(), createSubscriber(createIdentity(IDENTITY_NAME)));

        }
    });

}
 
Example 14
Source Project: webcurator   Source File: TargetDAOImpl.java    License: Apache License 2.0 6 votes vote down vote up
public void save(final Schedule aSchedule) {
	txTemplate.execute(
			new TransactionCallback() {
				public Object doInTransaction(TransactionStatus ts) {
					try { 
						log.debug("Before Saving of Schedule");
						getSession().saveOrUpdate(aSchedule);
						log.debug("After Saving Schedule");
					}
					catch(Exception ex) {
						log.debug("Setting Rollback Only", ex);
						ts.setRollbackOnly();
						throw new WCTRuntimeException("Failed to save schedule", ex);
					}
					return null;
				}
			}
	);	
}
 
Example 15
private List<Product> getProducts_Mercifully() {
    return transactionTemplate.execute(new TransactionCallback<List<Product>>() {
        @Override
        public List<Product> doInTransaction(TransactionStatus transactionStatus) {
            CriteriaBuilder cb = entityManager.getCriteriaBuilder();
            CriteriaQuery<Product> query = cb.createQuery(Product.class);
            Root<Image> imageRoot = query.from(Image.class);
            Join<Image, Product> productJoin = imageRoot.join(Image_.product);
            query.select(productJoin);
            query.distinct(true);
            List<Predicate> criteria = new ArrayList<Predicate>();
            criteria.add(cb.like(cb.lower(productJoin.get(Product_.name)), "%tv%"));
            criteria.add(cb.gt(imageRoot.get(Image_.index), 0));
            query.where(cb.and(criteria.toArray(new Predicate[criteria.size()])));
            return entityManager.createQuery(query).getResultList();
        }
    });
}
 
Example 16
/**
 * Check that a transaction is created and committed.
 */
@Test
public void transactionShouldSucceed() throws Exception {
	TransactionAttribute txatt = new DefaultTransactionAttribute();

	MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
	tas.register(getNameMethod, txatt);

	TransactionStatus status = mock(TransactionStatus.class);
	PlatformTransactionManager ptm = mock(PlatformTransactionManager.class);
	// expect a transaction
	given(ptm.getTransaction(txatt)).willReturn(status);

	TestBean tb = new TestBean();
	ITestBean itb = (ITestBean) advised(tb, ptm, tas);

	checkTransactionStatus(false);
	itb.getName();
	checkTransactionStatus(false);

	verify(ptm).commit(status);
}
 
Example 17
public String getUrl(String ref) {

        return transactionTemplate.execute(new TransactionCallback<String>() {

            @Override
            public String doInTransaction(TransactionStatus status) {

                AssignmentReferenceReckoner.AssignmentReference r = AssignmentReferenceReckoner.reckoner().reference(ref).reckon();

                try {
                    Site site = siteService.getSite(r.getContext());
                    ToolConfiguration fromTool = site.getToolForCommonId("sakai.assignment.grades");
                    return serverConfigurationService.getPortalUrl()
                            + "/directtool/"
                            + fromTool.getId()
                            + "?assignmentId="
                            + ref
                            + "&panel=Main&sakai_action=doView_assignment";
                } catch (Exception e) {
                    log.error("Failed to get deep link for context {} and assignment {}. Returning empty string.", r.getContext(), r.getId(), e);
                }
                return "";
            }
        });
    }
 
Example 18
Source Project: olat   Source File: MultithreadedDaoTestNgITCaseNew.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void setup() {
    new TransactionTemplate(txManager).execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            daoIdentity.setType(IdentityImpl.class);
            daoSubscriber.setType(Subscriber.class);
            daoPublisher.setType(Publisher.class);
            daoSubscription.setType(Subscription.class);

            createSubscription(createPublisher(), createSubscriber(createIdentity(IDENTITY_NAME)));

        }
    });

}
 
Example 19
@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();
}
 
Example 20
Source Project: gocd   Source File: MaterialRepositoryIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
private void assertCanLoadAndSaveMaterialRevisionsFor(MaterialConfig materialConfig) {
    final PipelineConfig pipelineConfig = PipelineMother.createPipelineConfig("mingle", new MaterialConfigs(materialConfig), "dev");

    final MaterialRevisions materialRevisions = ModificationsMother.modifyOneFile(pipelineConfig);
    MaterialRevision materialRevision = materialRevisions.getMaterialRevision(0);

    final Pipeline[] pipeline = new Pipeline[1];

    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            //assume that we have saved the materials
            repo.save(materialRevisions);

            PipelineConfig config = PipelineMother.withTwoStagesOneBuildEach("pipeline-name", "stage-1", "stage-2");
            config.setMaterialConfigs(materialRevisions.getMaterials().convertToConfigs());
            pipeline[0] = instanceFactory.createPipelineInstance(pipelineConfig, BuildCause.createManualForced(materialRevisions, Username.ANONYMOUS), new DefaultSchedulingContext(DEFAULT_APPROVED_BY), md5,
                    new TimeProvider());

            //this should persist the materials
            pipelineSqlMapDao.save(pipeline[0]);
        }
    });

    assertMaterialRevisions(materialRevision, pipeline[0]);
}
 
Example 21
Source Project: olat   Source File: PublishEventPerformance.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void publishEventManySubscriptionsForOnePublisher() {
    long startTime = System.currentTimeMillis();
    new TransactionTemplate(transactionManager).execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            int numEvents = notificationServiceImpl.publishEvent(getPublishEventTO());
            log.info("publishEventManySubscriptionsForOnePublisher - numEvents: " + numEvents);
            assertEquals(NUMBER_OF_SUBSCRIBERS * NUMBER_OF_PUBLISHERS, numEvents);
        }
    });
    long endTime = System.currentTimeMillis();
    long duration = (endTime - startTime) / 1000;
    log.info("DURATION in seconds: " + duration);
    assertTrue("maximal execution time for " + NUMBER_OF_SUBSCRIBERS + " subscriptions exceeded: maximal time in seconds: " + MAX_EXECUTION_TIME_IN_SECONDS
            + ", actual duration in seconds: " + duration, duration <= MAX_EXECUTION_TIME_IN_SECONDS);

}
 
Example 22
/**
 * If a transaction is currently active for the supplied
 * {@linkplain TestContext test context}, this method will end the transaction
 * and run {@link AfterTransaction @AfterTransaction} methods.
 * <p>{@code @AfterTransaction} methods are guaranteed to be invoked even if
 * an error occurs while ending the transaction.
 */
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
	Method testMethod = testContext.getTestMethod();
	Assert.notNull(testMethod, "The test method of the supplied TestContext must not be null");

	TransactionContext txContext = TransactionContextHolder.removeCurrentTransactionContext();
	// If there was (or perhaps still is) a transaction...
	if (txContext != null) {
		TransactionStatus transactionStatus = txContext.getTransactionStatus();
		try {
			// If the transaction is still active...
			if (transactionStatus != null && !transactionStatus.isCompleted()) {
				txContext.endTransaction();
			}
		}
		finally {
			runAfterTransactionMethods(testContext);
		}
	}
}
 
Example 23
Source Project: olat   Source File: UpdateEventsITCaseNew.java    License: Apache License 2.0 5 votes vote down vote up
private List<Subscriber> generateSubscribers() {
    return new TransactionTemplate(transactionManager).execute(new TransactionCallback<List<Subscriber>>() {
        public List<Subscriber> doInTransaction(TransactionStatus status) {
            return notificationTestDataGenerator.generateSubscribers(NUMBER_OF_SUBSCRIBERS);
        }
    });
}
 
Example 24
Source Project: sdn-rx   Source File: Neo4jTransactionManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void shouldUseTxFromNeo4jTxManager() {

	Neo4jTransactionManager txManager = new Neo4jTransactionManager(driver, DatabaseSelectionProvider.createStaticDatabaseSelectionProvider(databaseName));
	TransactionTemplate txTemplate = new TransactionTemplate(txManager);

	txTemplate.execute(new TransactionCallbackWithoutResult() {

		@Override
		protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {

			assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
			assertThat(transactionStatus.isNewTransaction()).isTrue();
			assertThat(TransactionSynchronizationManager.hasResource(driver)).isTrue();

			Transaction optionalTransaction = retrieveTransaction(driver, databaseName);
			assertThat(optionalTransaction).isNotNull();

			transactionStatus.setRollbackOnly();
		}
	});

	verify(driver).session(any(SessionConfig.class));

	verify(session).isOpen();
	verify(session).beginTransaction(any(TransactionConfig.class));
	verify(session).close();

	verify(transaction, times(2)).isOpen();
	verify(transaction).rollback();
	verify(transaction).close();
}
 
Example 25
Source Project: sdn-rx   Source File: Neo4jTransactionManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void shouldParticipateInOngoingTransactionWithCommit() throws Exception {

	when(userTransaction.getStatus()).thenReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE,
			Status.STATUS_ACTIVE);

	JtaTransactionManager txManager = new JtaTransactionManager(userTransaction);
	TransactionTemplate txTemplate = new TransactionTemplate(txManager);

	txTemplate.execute(new TransactionCallbackWithoutResult() {

		@Override
		protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {

			assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
			assertThat(transactionStatus.isNewTransaction()).isTrue();
			assertThat(TransactionSynchronizationManager.hasResource(driver)).isFalse();

			Transaction nativeTransaction = retrieveTransaction(driver, databaseName);

			assertThat(nativeTransaction).isNotNull();
			assertThat(TransactionSynchronizationManager.hasResource(driver)).isTrue();
		}
	});

	verify(userTransaction).begin();

	verify(driver).session(any(SessionConfig.class));

	verify(session, times(2)).isOpen();
	verify(session).beginTransaction(any(TransactionConfig.class));
	verify(session).close();

	verify(transaction, times(3)).isOpen();
	verify(transaction).commit();
	verify(transaction).close();
}
 
Example 26
/** {@inheritDoc} */
@Override
protected void endTx(final Object tx) {
    final TransactionStatus transaction = (TransactionStatus) tx;
    transaction.setRollbackOnly(); // Read only transactions
    this.platformTransactionManager.commit(transaction);
}
 
Example 27
/**
 * 触发事务开始方法 
 */
protected void triggerBegin(TransactionStatus status)throws Throwable{
	Map<Object, TransactionResource> trs = TransactionResourceManager.getResourceMap();
	for (TransactionResource tr : trs.values()) {
		tr.begin();
	}
}
 
Example 28
@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());
}
 
Example 29
Source Project: gocd   Source File: DatabaseAccessHelper.java    License: Apache License 2.0 5 votes vote down vote up
private void updateResultInTransaction(final Stage stage, final StageResult stageResult) {
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            stageDao.updateResult(stage, stageResult, null);
        }
    });
}
 
Example 30
Source Project: spring-analysis-note   Source File: TransactionAspectSupport.java    License: MIT License 5 votes vote down vote up
/**
 * Create a transaction if necessary based on the given TransactionAttribute.
 * <p>Allows callers to perform custom TransactionAttribute lookups through
 * the TransactionAttributeSource.
 * @param txAttr the TransactionAttribute (may be {@code null})
 * @param joinpointIdentification the fully qualified method name
 * (used for monitoring and logging purposes)
 * @return a TransactionInfo object, whether or not a transaction was created.
 * The {@code hasTransaction()} method on TransactionInfo can be used to
 * tell if there was a transaction created.
 * @see #getTransactionAttributeSource()
 */
@SuppressWarnings("serial")
protected TransactionInfo createTransactionIfNecessary(@Nullable PlatformTransactionManager tm,
		@Nullable TransactionAttribute txAttr, final String joinpointIdentification) {

	// If no name specified, apply method identification as transaction name.
	// 如果没有名称指定则使用方法唯一标识,并使用 DelegatingTransactionAttribute 包装 txAttr
	if (txAttr != null && txAttr.getName() == null) {
		txAttr = new DelegatingTransactionAttribute(txAttr) {
			@Override
			public String getName() {
				return joinpointIdentification;
			}
		};
	}

	TransactionStatus status = null;
	if (txAttr != null) {
		if (tm != null) {
			// 获取 TransactionStatus
			status = tm.getTransaction(txAttr);
		}
		else {
			if (logger.isDebugEnabled()) {
				logger.debug("Skipping transactional joinpoint [" + joinpointIdentification +
						"] because no transaction manager has been configured");
			}
		}
	}
	// 根据指定的属性与 status 准备一个 TransactionInfo
	return prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);
}