org.springframework.transaction.support.TransactionSynchronizationManager Java Examples

The following examples show how to use org.springframework.transaction.support.TransactionSynchronizationManager. 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: HibernateCriteriaBuilder.java    From gorm-hibernate5 with Apache License 2.0 6 votes vote down vote up
@Override
protected void createCriteriaInstance() {
    {
        if (TransactionSynchronizationManager.hasResource(sessionFactory)) {
            participate = true;
            hibernateSession = ((SessionHolder)TransactionSynchronizationManager.getResource(sessionFactory)).getSession();
        }
        else {
            hibernateSession = sessionFactory.openSession();
        }

        criteria = hibernateSession.createCriteria(targetClass);
        cacheCriteriaMapping();
        criteriaMetaClass = GroovySystem.getMetaClassRegistry().getMetaClass(criteria.getClass());
    }
}
 
Example #2
Source File: HibernateTemplateTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteWithThreadBoundAndParameterizedFilter() {
	Filter filter = mock(Filter.class);
	given(session.isOpen()).willReturn(true);
	given(session.enableFilter("myFilter")).willReturn(filter);
	hibernateTemplate.setAllowCreate(false);
	hibernateTemplate.setFilterName("myFilter");

	TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
	try {
		final List l = new ArrayList();
		l.add("test");
		Filter f = hibernateTemplate.enableFilter("myFilter");
		assertTrue("Correct filter", f == filter);
	}
	finally {
		TransactionSynchronizationManager.unbindResource(sessionFactory);
	}
	InOrder ordered = inOrder(session);
	ordered.verify(session).getEnabledFilter("myFilter");
	ordered.verify(session).enableFilter("myFilter");
}
 
Example #3
Source File: EntityManagerFactoryUtils.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected void flushResource(EntityManagerHolder resourceHolder) {
	EntityManager em = resourceHolder.getEntityManager();
	if (em instanceof EntityManagerProxy) {
		EntityManager target = ((EntityManagerProxy) em).getTargetEntityManager();
		if (TransactionSynchronizationManager.hasResource(target)) {
			// ExtendedEntityManagerSynchronization active after joinTransaction() call:
			// flush synchronization already registered.
			return;
		}
	}
	try {
		em.flush();
	}
	catch (RuntimeException ex) {
		DataAccessException dae;
		if (this.jpaDialect != null) {
			dae = this.jpaDialect.translateExceptionIfPossible(ex);
		}
		else {
			dae = convertJpaAccessExceptionIfPossible(ex);
		}
		throw (dae != null ? dae : ex);
	}
}
 
Example #4
Source File: HibernateTemplate.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Prepare the given Query object, applying cache settings and/or
 * a transaction timeout.
 * @param queryObject the Query object to prepare
 * @see #setCacheQueries
 * @see #setQueryCacheRegion
 */
@SuppressWarnings({"rawtypes", "deprecation"})
protected void prepareQuery(org.hibernate.Query queryObject) {
	if (isCacheQueries()) {
		queryObject.setCacheable(true);
		if (getQueryCacheRegion() != null) {
			queryObject.setCacheRegion(getQueryCacheRegion());
		}
	}
	if (getFetchSize() > 0) {
		queryObject.setFetchSize(getFetchSize());
	}
	if (getMaxResults() > 0) {
		queryObject.setMaxResults(getMaxResults());
	}

	ResourceHolderSupport sessionHolder =
			(ResourceHolderSupport) TransactionSynchronizationManager.getResource(obtainSessionFactory());
	if (sessionHolder != null && sessionHolder.hasTimeout()) {
		queryObject.setTimeout(sessionHolder.getTimeToLiveInSeconds());
	}
}
 
Example #5
Source File: ContextSourceAndHibernateTransactionManagerNamespaceITest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Before
public void prepareTest() throws Exception {
	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		TransactionSynchronizationManager.clearSynchronization();
	}

	OrgPerson person = new OrgPerson();
	person.setId(new Integer(1));
	person.setLastname("Person");
	person.setFullname("Some Person");
	person.setDescription("Sweden, Company1, Some Person");
	person.setCountry("Sweden");
	person.setCompany("Company1");
	// "Some Person", "Person", "Sweden, Company1, Some Person"
	// avoid the transaction manager we have configured, do it manually
	Session session = this.sessionFactory.openSession();
	Transaction tx = session.beginTransaction();
	session.saveOrUpdate(person);
	tx.commit();
	session.close();

}
 
Example #6
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 #7
Source File: DataSourceTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #8
Source File: DataSourceTransactionManagerTests.java    From effectivejava with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #9
Source File: TransactionalEventListenerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void beforeCommitWithException() { // Validates the custom synchronization is invoked
	load(BeforeCommitTestListener.class);
	try {
		this.transactionTemplate.execute(status -> {
			TransactionSynchronizationManager.registerSynchronization(new EventTransactionSynchronization(10) {
				@Override
				public void beforeCommit(boolean readOnly) {
					throw new IllegalStateException("test");
				}
			});
			getContext().publishEvent("test");
			getEventCollector().assertNoEventReceived();
			return null;

		});
		fail("Should have thrown an exception");
	}
	catch (IllegalStateException e) {
		// Test exception - ignore
	}
	getEventCollector().assertNoEventReceived(); // Before commit not invoked
}
 
Example #10
Source File: DataSourceUtils.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void afterCompletion(int status) {
	// If we haven't closed the Connection in beforeCompletion,
	// close it now. The holder might have been used for other
	// cleanup in the meantime, for example by a Hibernate Session.
	if (this.holderActive) {
		// The thread-bound ConnectionHolder might not be available anymore,
		// since afterCompletion might get called from a different thread.
		TransactionSynchronizationManager.unbindResourceIfPossible(this.dataSource);
		this.holderActive = false;
		if (this.connectionHolder.hasConnection()) {
			releaseConnection(this.connectionHolder.getConnection(), this.dataSource);
			// Reset the ConnectionHolder: It might remain bound to the thread.
			this.connectionHolder.setConnection(null);
		}
	}
	this.connectionHolder.reset();
}
 
Example #11
Source File: StoredProcedureTests.java    From effectivejava with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddInvoicesWithinTransaction() throws Exception {
	given(callableStatement.execute()).willReturn(false);
	given(callableStatement.getUpdateCount()).willReturn(-1);
	given(callableStatement.getObject(3)).willReturn(4);
	given(connection.prepareCall("{call " + AddInvoice.SQL + "(?, ?, ?)}")
			).willReturn(callableStatement);
	TransactionSynchronizationManager.bindResource(dataSource, new ConnectionHolder(connection));
	try {
		testAddInvoice(1106, 3);
		verify(callableStatement).setObject(1, 1106, Types.INTEGER);
		verify(callableStatement).setObject(2, 3, Types.INTEGER);
		verify(callableStatement).registerOutParameter(3, Types.INTEGER);
		verify(connection, never()).close();
	}
	finally {
		TransactionSynchronizationManager.unbindResource(dataSource);
		connection.close();
	}
}
 
Example #12
Source File: HibernateInterceptorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testInterceptorWithThreadBoundAndFlushEagerSwitch() throws HibernateException {
	given(session.isOpen()).willReturn(true);
	given(session.getFlushMode()).willReturn(FlushMode.NEVER);

	TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
	HibernateInterceptor interceptor = new HibernateInterceptor();
	interceptor.setFlushMode(HibernateInterceptor.FLUSH_EAGER);
	interceptor.setSessionFactory(sessionFactory);
	try {
		interceptor.invoke(invocation);
	}
	catch (Throwable t) {
		fail("Should not have thrown Throwable: " + t.getMessage());
	}
	finally {
		TransactionSynchronizationManager.unbindResource(sessionFactory);
	}

	InOrder ordered = inOrder(session);
	ordered.verify(session).setFlushMode(FlushMode.AUTO);
	ordered.verify(session).flush();
	ordered.verify(session).setFlushMode(FlushMode.NEVER);
}
 
Example #13
Source File: ApplicationListenerMethodTransactionalAdapter.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEvent event) {
	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		TransactionSynchronization transactionSynchronization = createTransactionSynchronization(event);
		TransactionSynchronizationManager.registerSynchronization(transactionSynchronization);
	}
	else if (this.annotation.fallbackExecution()) {
		if (this.annotation.phase() == TransactionPhase.AFTER_ROLLBACK && logger.isWarnEnabled()) {
			logger.warn("Processing " + event + " as a fallback execution on AFTER_ROLLBACK phase");
		}
		processEvent(event);
	}
	else {
		// No transactional event execution at all
		if (logger.isDebugEnabled()) {
			logger.debug("No transaction is active - skipping " + event);
		}
	}
}
 
Example #14
Source File: DataSourceUtils.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void afterCompletion(int status) {
	// If we haven't closed the Connection in beforeCompletion,
	// close it now. The holder might have been used for other
	// cleanup in the meantime, for example by a Hibernate Session.
	if (this.holderActive) {
		// The thread-bound ConnectionHolder might not be available anymore,
		// since afterCompletion might get called from a different thread.
		TransactionSynchronizationManager.unbindResourceIfPossible(this.dataSource);
		this.holderActive = false;
		if (this.connectionHolder.hasConnection()) {
			releaseConnection(this.connectionHolder.getConnection(), this.dataSource);
			// Reset the ConnectionHolder: It might remain bound to the thread.
			this.connectionHolder.setConnection(null);
		}
	}
	this.connectionHolder.reset();
}
 
Example #15
Source File: Db.java    From Aooms with Apache License 2.0 6 votes vote down vote up
/**
 * 注意:开启	@Transactional 时无法使用该方法
 */
public void useOn(String name) {
    Assert.notNull(name,"datasource name is not allow null !");
    // 如果包含在当前spring事务中,拒绝操作
    if(TransactionSynchronizationManager.isActualTransactionActive()){
        throw new UnsupportedOperationException("Cannot be used in spring transactions !");
    }

    if (!DynamicDataSourceHolder.containsDataSource(name)) {
        logger.error("datasource [{}] not found !",name);
    } else {
        logger.info("on datasource [{}]",name);
        // 设置动态数据源上下文
        DynamicDataSourceHolder.setDataSource(name);
    }
}
 
Example #16
Source File: SpringSessionSynchronization.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
@SuppressWarnings("deprecation")
public void beforeCompletion() {
	try {
		Session session = this.sessionHolder.getSession();
		if (this.sessionHolder.getPreviousFlushMode() != null) {
			// In case of pre-bound Session, restore previous flush mode.
			session.setFlushMode(this.sessionHolder.getPreviousFlushMode());
		}
		// Eagerly disconnect the Session here, to make release mode "on_close" work nicely.
		session.disconnect();
	}
	finally {
		// Unbind at this point if it's a new Session...
		if (this.newSession) {
			TransactionSynchronizationManager.unbindResource(this.sessionFactory);
			this.holderActive = false;
		}
	}
}
 
Example #17
Source File: DataSourceUtils.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Apply the specified timeout - overridden by the current transaction timeout,
 * if any - to the given JDBC Statement object.
 * @param stmt the JDBC Statement object
 * @param dataSource the DataSource that the Connection was obtained from
 * @param timeout the timeout to apply (or 0 for no timeout outside of a transaction)
 * @throws SQLException if thrown by JDBC methods
 * @see java.sql.Statement#setQueryTimeout
 */
public static void applyTimeout(Statement stmt, @Nullable DataSource dataSource, int timeout) throws SQLException {
	Assert.notNull(stmt, "No Statement specified");
	ConnectionHolder holder = null;
	if (dataSource != null) {
		holder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource);
	}
	if (holder != null && holder.hasTimeout()) {
		// Remaining transaction timeout overrides specified value.
		stmt.setQueryTimeout(holder.getTimeToLiveInSeconds());
	}
	else if (timeout >= 0) {
		// No current transaction timeout -> apply specified value.
		stmt.setQueryTimeout(timeout);
	}
}
 
Example #18
Source File: ApplicationListenerMethodTransactionalAdapter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEvent event) {
	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		TransactionSynchronization transactionSynchronization = createTransactionSynchronization(event);
		TransactionSynchronizationManager.registerSynchronization(transactionSynchronization);
	}
	else if (this.annotation.fallbackExecution()) {
		if (this.annotation.phase() == TransactionPhase.AFTER_ROLLBACK) {
			logger.warn("Processing '" + event + "' as a fallback execution on AFTER_ROLLBACK phase.");
		}
		processEvent(event);
	}
	else {
		if (logger.isDebugEnabled()) {
			logger.debug("No transaction is running, skipping '" + event + "' for '" + this + "'");
		}
	}
}
 
Example #19
Source File: SpringSessionSynchronization.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void beforeCompletion() {
	try {
		Session session = this.sessionHolder.getSession();
		if (this.sessionHolder.getPreviousFlushMode() != null) {
			// In case of pre-bound Session, restore previous flush mode.
			session.setFlushMode(this.sessionHolder.getPreviousFlushMode());
		}
		// Eagerly disconnect the Session here, to make release mode "on_close" work nicely.
		session.disconnect();
	}
	finally {
		// Unbind at this point if it's a new Session...
		if (this.newSession) {
			TransactionSynchronizationManager.unbindResource(this.sessionFactory);
			this.holderActive = false;
		}
	}
}
 
Example #20
Source File: ApplicationListenerMethodTransactionalAdapter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEvent event) {
	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		TransactionSynchronization transactionSynchronization = createTransactionSynchronization(event);
		TransactionSynchronizationManager.registerSynchronization(transactionSynchronization);
	}
	else if (this.annotation.fallbackExecution()) {
		if (this.annotation.phase() == TransactionPhase.AFTER_ROLLBACK && logger.isWarnEnabled()) {
			logger.warn("Processing " + event + " as a fallback execution on AFTER_ROLLBACK phase");
		}
		processEvent(event);
	}
	else {
		// No transactional event execution at all
		if (logger.isDebugEnabled()) {
			logger.debug("No transaction is active - skipping " + event);
		}
	}
}
 
Example #21
Source File: SessionFactoryUtils.java    From mycollab with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Get a JCR Session for the given Repository. Is aware of and will return any existing corresponding
 * Session bound to the current thread, for example when using JcrTransactionManager. Same as
 * <code>getSession</code> but throws the original Repository.
 * @param sessionFactory Jcr Repository to create session with
 * @param allowCreate if a non-transactional Session should be created when no transactional Session can
 *            be found for the current thread
 * @throws RepositoryException
 * @return
 */
public static Session doGetSession(SessionFactory sessionFactory, boolean allowCreate) throws RepositoryException {
    Assert.notNull(sessionFactory, "No sessionFactory specified");

    // check if there is any transaction going on
    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
    if (sessionHolder != null && sessionHolder.getSession() != null)
        return sessionHolder.getSession();

    if (!allowCreate && !TransactionSynchronizationManager.isSynchronizationActive()) {
        throw new IllegalStateException("No session bound to thread, " + "and configuration does not allow creation of non-transactional one here");
    }

    LOG.debug("Opening JCR Session");
    Session session = sessionFactory.getSession();

    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        LOG.debug("Registering transaction synchronization for JCR session");
        // Use same session for further JCR actions within the transaction
        // thread object will get removed by synchronization at transaction
        // completion.
        sessionHolder = sessionFactory.getSessionHolder(session);
        sessionHolder.setSynchronizedWithTransaction(true);
        TransactionSynchronizationManager.registerSynchronization(new JcrSessionSynchronization(sessionHolder, sessionFactory));
        TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder);
    }

    return session;
}
 
Example #22
Source File: HibernateTransactionManager.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected void doResume(Object transaction, Object suspendedResources) {
	SuspendedResourcesHolder resourcesHolder = (SuspendedResourcesHolder) suspendedResources;
	if (TransactionSynchronizationManager.hasResource(getSessionFactory())) {
		// From non-transactional code running in active transaction synchronization
		// -> can be safely removed, will be closed on transaction completion.
		TransactionSynchronizationManager.unbindResource(getSessionFactory());
	}
	TransactionSynchronizationManager.bindResource(getSessionFactory(), resourcesHolder.getSessionHolder());
	if (getDataSource() != null) {
		TransactionSynchronizationManager.bindResource(getDataSource(), resourcesHolder.getConnectionHolder());
	}
}
 
Example #23
Source File: JtaTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void jtaTransactionManagerWithCommitAndSynchronizationOnActual() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);

	final TransactionSynchronization synch = mock(TransactionSynchronization.class);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	ptm.setTransactionSynchronization(JtaTransactionManager.SYNCHRONIZATION_ON_ACTUAL_TRANSACTION);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			// something transactional
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			TransactionSynchronizationManager.registerSynchronization(synch);
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(ut).begin();
	verify(ut).commit();
	verify(synch).beforeCommit(false);
	verify(synch).beforeCompletion();
	verify(synch).afterCommit();
	verify(synch).afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
}
 
Example #24
Source File: JpaTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testTransactionCommitWithPropagationSupports() {
	given(manager.isOpen()).willReturn(true);

	final List<String> l = new ArrayList<String>();
	l.add("test");

	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);

	assertTrue(!TransactionSynchronizationManager.hasResource(factory));
	assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());

	Object result = tt.execute(new TransactionCallback() {
		@Override
		public Object doInTransaction(TransactionStatus status) {
			assertTrue(!TransactionSynchronizationManager.hasResource(factory));
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			assertTrue(!status.isNewTransaction());
			EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
			return l;
		}
	});
	assertSame(l, result);

	assertTrue(!TransactionSynchronizationManager.hasResource(factory));
	assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());

	verify(manager).flush();
	verify(manager).close();
}
 
Example #25
Source File: SpringJtaSessionContext.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected Session buildOrObtainSession() {
	Session session = super.buildOrObtainSession();
	if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
		session.setFlushMode(FlushMode.MANUAL);
	}
	return session;
}
 
Example #26
Source File: ConnectionFactoryUtils.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Determine whether the given JMS Session is transactional, that is,
 * bound to the current thread by Spring's transaction facilities.
 * @param session the JMS Session to check
 * @param cf the JMS ConnectionFactory that the Session originated from
 * @return whether the Session is transactional
 */
public static boolean isSessionTransactional(@Nullable Session session, @Nullable ConnectionFactory cf) {
	if (session == null || cf == null) {
		return false;
	}
	JmsResourceHolder resourceHolder = (JmsResourceHolder) TransactionSynchronizationManager.getResource(cf);
	return (resourceHolder != null && resourceHolder.containsSession(session));
}
 
Example #27
Source File: DataSourceTransactionManagerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testTransactionAwareDataSourceProxy() throws Exception {
	given(con.getAutoCommit()).willReturn(true);

	TransactionTemplate tt = new TransactionTemplate(tm);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			// something transactional
			assertEquals(con, DataSourceUtils.getConnection(ds));
			TransactionAwareDataSourceProxy dsProxy = new TransactionAwareDataSourceProxy(ds);
			try {
				assertEquals(con, ((ConnectionProxy) dsProxy.getConnection()).getTargetConnection());
				// should be ignored
				dsProxy.getConnection().close();
			}
			catch (SQLException ex) {
				throw new UncategorizedSQLException("", "", ex);
			}
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	InOrder ordered = inOrder(con);
	ordered.verify(con).setAutoCommit(false);
	ordered.verify(con).commit();
	ordered.verify(con).setAutoCommit(true);
	verify(con).close();
}
 
Example #28
Source File: JtaTransactionManagerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void jtaTransactionManagerWithExistingTransactionAndJtaSynchronization() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	TransactionManager tm = mock(TransactionManager.class);
	MockJtaTransaction tx = new MockJtaTransaction();

	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);
	given(tm.getTransaction()).willReturn(tx);

	final TransactionSynchronization synch = mock(TransactionSynchronization.class);

	JtaTransactionManager ptm = newJtaTransactionManager(ut, tm);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			TransactionSynchronizationManager.registerSynchronization(synch);
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	assertNotNull(tx.getSynchronization());
	tx.getSynchronization().beforeCompletion();
	tx.getSynchronization().afterCompletion(Status.STATUS_ROLLEDBACK);

	verify(ut).setRollbackOnly();
	verify(synch).beforeCompletion();
	verify(synch).afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK);
}
 
Example #29
Source File: IsolationLevelDataSourceAdapter.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Determine the current isolation level: either the transaction's
 * isolation level or a statically defined isolation level.
 * @return the current isolation level, or {@code null} if none
 * @see org.springframework.transaction.support.TransactionSynchronizationManager#getCurrentTransactionIsolationLevel()
 * @see #setIsolationLevel
 */
@Nullable
protected Integer getCurrentIsolationLevel() {
	Integer isolationLevelToUse = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel();
	if (isolationLevelToUse == null) {
		isolationLevelToUse = getIsolationLevel();
	}
	return isolationLevelToUse;
}
 
Example #30
Source File: TransactionalRepositoryDecorator.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void forEachBatched(Consumer<List<E>> consumer, int batchSize) {
  if (TransactionSynchronizationManager.isSynchronizationActive()) {
    delegate().forEachBatched(consumer, batchSize);
  } else {
    createReadonlyTransactionTemplate()
        .execute(
            status -> {
              delegate().forEachBatched(consumer, batchSize);
              return null;
            });
  }
}