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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
Source File: AbstractLockStore.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Returns a transactionally scoped Map that is used to provide repeatable lock store queries
 * for a given NodeRef. If no transaction is present, then null is returned.
 * 
 * @return Transactional Map or null if not available.
 */
protected Map<NodeRef, LockState> getTxMap()
{
    if (!TransactionSynchronizationManager.isSynchronizationActive())
    {
        return null;
    }
    Map<NodeRef, LockState> map = TransactionalResourceHelper.getMap(getClass().getName()+".repeatableReadMap");
    return map;
}
 
Example #22
Source File: DataSourceUtils.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void suspend() {
	if (this.holderActive) {
		TransactionSynchronizationManager.unbindResource(this.dataSource);
		if (this.connectionHolder.hasConnection() && !this.connectionHolder.isOpen()) {
			// Release Connection on suspend if the application doesn't keep
			// a handle to it anymore. We will fetch a fresh Connection if the
			// application accesses the ConnectionHolder again after resume,
			// assuming that it will participate in the same transaction.
			releaseConnection(this.connectionHolder.getConnection(), this.dataSource);
			this.connectionHolder.setConnection(null);
		}
	}
}
 
Example #23
Source File: JpaTransactionManagerHandlerTest.java    From opensharding-spi-impl with Apache License 2.0 5 votes vote down vote up
@Test
public void assertUnbindResource() {
    EntityManagerHolder holder = mock(EntityManagerHolder.class);
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    when(holder.getEntityManager()).thenReturn(entityManager);
    TransactionSynchronizationManager.bindResource(entityManagerFactory, holder);
    jpaTransactionManagerHandler.unbindResource();
    assertNull(TransactionSynchronizationManager.getResource(entityManagerFactory));
}
 
Example #24
Source File: TransactionAwareCacheDecorator.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void clear() {
	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
			@Override
			public void afterCommit() {
				targetCache.clear();
			}
		});
	}
	else {
		this.targetCache.clear();
	}
}
 
Example #25
Source File: DataSourceTransactionManagerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testTransactionWithIsolationAndReadOnly() throws Exception {
	given(con.getTransactionIsolation()).willReturn(Connection.TRANSACTION_READ_COMMITTED);
	given(con.getAutoCommit()).willReturn(true);

	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
	tt.setReadOnly(true);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			// something transactional
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	InOrder ordered = inOrder(con);
	ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
	ordered.verify(con).setAutoCommit(false);
	ordered.verify(con).commit();
	ordered.verify(con).setAutoCommit(true);
	ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
	verify(con).close();
}
 
Example #26
Source File: JpaTransactionManager.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected void doCleanupAfterCompletion(Object transaction) {
	JpaTransactionObject txObject = (JpaTransactionObject) transaction;

	// Remove the entity manager holder from the thread, if still there.
	// (Could have been removed by EntityManagerFactoryUtils in order
	// to replace it with an unsynchronized EntityManager).
	if (txObject.isNewEntityManagerHolder()) {
		TransactionSynchronizationManager.unbindResourceIfPossible(getEntityManagerFactory());
	}
	txObject.getEntityManagerHolder().clear();

	// Remove the JDBC connection holder from the thread, if exposed.
	if (txObject.hasConnectionHolder()) {
		TransactionSynchronizationManager.unbindResource(getDataSource());
		try {
			getJpaDialect().releaseJdbcConnection(txObject.getConnectionHolder().getConnectionHandle(),
					txObject.getEntityManagerHolder().getEntityManager());
		}
		catch (Exception ex) {
			// Just log it, to keep a transaction-related exception.
			logger.error("Could not close JDBC connection after transaction", ex);
		}
	}

	getJpaDialect().cleanupTransaction(txObject.getTransactionData());

	// Remove the entity manager holder from the thread.
	if (txObject.isNewEntityManagerHolder()) {
		EntityManager em = txObject.getEntityManagerHolder().getEntityManager();
		if (logger.isDebugEnabled()) {
			logger.debug("Closing JPA EntityManager [" + em + "] after transaction");
		}
		EntityManagerFactoryUtils.closeEntityManager(em);
	}
	else {
		logger.debug("Not closing pre-bound JPA EntityManager after transaction");
	}
}
 
Example #27
Source File: HibernateJtaTransactionTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void testJtaSessionSynchronization() throws Exception {

	TransactionManager tm = mock(TransactionManager.class);
	MockJtaTransaction transaction = new MockJtaTransaction();
	given(tm.getTransaction()).willReturn(transaction);
	final SessionFactoryImplementor sf = mock(SessionFactoryImplementor.class);
	final Session session = mock(Session.class);
	given(sf.openSession()).willReturn(session);
	given(sf.getTransactionManager()).willReturn(tm);
	given(session.isOpen()).willReturn(true);
	given(session.getFlushMode()).willReturn(FlushMode.AUTO);

	assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
	HibernateTemplate ht = new HibernateTemplate(sf);
	ht.setExposeNativeSession(true);
	for (int i = 0; i < 5; i++) {
		ht.executeFind(new HibernateCallback() {

			@Override
			public Object doInHibernate(org.hibernate.Session sess) {
				assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
				assertEquals(session, sess);
				return null;
			}
		});
	}

	Synchronization synchronization = transaction.getSynchronization();
	assertTrue("JTA synchronization registered", synchronization != null);
	synchronization.beforeCompletion();
	synchronization.afterCompletion(Status.STATUS_COMMITTED);

	assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
	assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

	verify(session).flush();
	verify(session).close();
}
 
Example #28
Source File: DataSourceTransactionManagerTests.java    From effectivejava with Apache License 2.0 5 votes vote down vote up
@Test
public void testTransactionRollbackOnly() throws Exception {
	tm.setTransactionSynchronization(DataSourceTransactionManager.SYNCHRONIZATION_NEVER);
	TransactionTemplate tt = new TransactionTemplate(tm);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive());

	ConnectionHolder conHolder = new ConnectionHolder(con);
	conHolder.setTransactionActive(true);
	TransactionSynchronizationManager.bindResource(ds, conHolder);
	final RuntimeException ex = new RuntimeException("Application exception");
	try {
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
				assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds));
				assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive());
				assertTrue("Is existing transaction", !status.isNewTransaction());
				throw ex;
			}
		});
		fail("Should have thrown RuntimeException");
	}
	catch (RuntimeException ex2) {
		// expected
		assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive());
		assertEquals("Correct exception thrown", ex, ex2);
	}
	finally {
		TransactionSynchronizationManager.unbindResource(ds);
	}

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
}
 
Example #29
Source File: IndexPicDaoTest.java    From wetech-cms with MIT License 5 votes vote down vote up
@After
public void tearDown() throws DatabaseUnitException, SQLException, IOException {
	SessionHolder holder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
	Session s = holder.getSession(); 
	s.flush();
	TransactionSynchronizationManager.unbindResource(sessionFactory);
}
 
Example #30
Source File: SpringSessionSynchronization.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void suspend() {
	if (this.holderActive) {
		TransactionSynchronizationManager.unbindResource(this.sessionFactory);
		// Eagerly disconnect the Session here, to make release mode "on_close" work on JBoss.
		getCurrentSession().disconnect();
	}
}