Java Code Examples for org.springframework.transaction.support.TransactionSynchronizationManager#unbindResource()

The following examples show how to use org.springframework.transaction.support.TransactionSynchronizationManager#unbindResource() . 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: SpringSessionSynchronization.java    From java-technology-stack with MIT License 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 2
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 3
Source File: OpenSessionInterceptor.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
	SessionFactory sf = getSessionFactory();
	if (!TransactionSynchronizationManager.hasResource(sf)) {
		// New Session to be bound for the current method's scope...
		Session session = openSession();
		try {
			TransactionSynchronizationManager.bindResource(sf, new org.springframework.orm.hibernate3.SessionHolder(session));
			return invocation.proceed();
		}
		finally {
			org.springframework.orm.hibernate3.SessionFactoryUtils.closeSession(session);
			TransactionSynchronizationManager.unbindResource(sf);
		}
	}
	else {
		// Pre-bound Session found -> simply proceed.
		return invocation.proceed();
	}
}
 
Example 4
Source File: JcrInterceptor.java    From mycollab with GNU Affero General Public License v3.0 6 votes vote down vote up
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
    boolean existingTransaction = false;
    Session session = SessionFactoryUtils.getSession(getSessionFactory(), true);
    if (TransactionSynchronizationManager.hasResource(getSessionFactory())) {
        LOG.debug("Found thread-bound Session for JCR interceptor");
        existingTransaction = true;
    } else {
        LOG.debug("Using new Session for JCR interceptor");
        TransactionSynchronizationManager.bindResource(getSessionFactory(), getSessionFactory().getSessionHolder(session));
    }
    try {
        Object retVal = methodInvocation.proceed();
        // flushIfNecessary(session, existingTransaction);
        return retVal;
    } finally {
        if (existingTransaction) {
            LOG.debug("Not closing pre-bound JCR Session after interceptor");
        } else {
            TransactionSynchronizationManager.unbindResource(getSessionFactory());
            SessionFactoryUtils.releaseSession(session, getSessionFactory());
        }
    }
}
 
Example 5
Source File: OpenSessionInterceptor.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
	SessionFactory sf = getSessionFactory();
	if (!TransactionSynchronizationManager.hasResource(sf)) {
		// New Session to be bound for the current method's scope...
		Session session = openSession();
		try {
			TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session));
			return invocation.proceed();
		}
		finally {
			SessionFactoryUtils.closeSession(session);
			TransactionSynchronizationManager.unbindResource(sf);
		}
	}
	else {
		// Pre-bound Session found -> simply proceed.
		return invocation.proceed();
	}
}
 
Example 6
Source File: HibernatePersistenceContextInterceptor.java    From gorm-hibernate5 with Apache License 2.0 6 votes vote down vote up
public void destroy() {
    DeferredBindingActions.clear();
    if(!disconnected.isEmpty()) {
        disconnected.pop();
    }
    if (getSessionFactory() == null || decNestingCount() > 0 || getParticipate()) {
        return;
    }

    // single session mode
    SessionHolder holder = (SessionHolder) TransactionSynchronizationManager.unbindResource(getSessionFactory());
    LOG.debug("Closing single Hibernate session in GrailsDispatcherServlet");
    try {
        disconnected.clear();
        SessionFactoryUtils.closeSession(holder.getSession());
    }
    catch (RuntimeException ex) {
        LOG.error("Unexpected exception on closing Hibernate Session", ex);
    }
}
 
Example 7
Source File: SimpleMessageListenerContainer.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Process a message received from the provider.
 * <p>Executes the listener, exposing the current JMS Session as
 * thread-bound resource (if "exposeListenerSession" is "true").
 * @param message the received JMS Message
 * @param session the JMS Session to operate on
 * @see #executeListener
 * @see #setExposeListenerSession
 */
protected void processMessage(Message message, Session session) {
	ConnectionFactory connectionFactory = getConnectionFactory();
	boolean exposeResource = (connectionFactory != null && isExposeListenerSession());
	if (exposeResource) {
		TransactionSynchronizationManager.bindResource(
				connectionFactory, new LocallyExposedJmsResourceHolder(session));
	}
	try {
		executeListener(session, message);
	}
	finally {
		if (exposeResource) {
			TransactionSynchronizationManager.unbindResource(getConnectionFactory());
		}
	}
}
 
Example 8
Source File: JmsTransactionManager.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected void doCleanupAfterCompletion(Object transaction) {
	JmsTransactionObject txObject = (JmsTransactionObject) transaction;
	TransactionSynchronizationManager.unbindResource(obtainConnectionFactory());
	txObject.getResourceHolder().closeAll();
	txObject.getResourceHolder().clear();
}
 
Example 9
Source File: JpaTransactionManagerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testTransactionRollbackWithPrebound() {
	given(manager.getTransaction()).willReturn(tx);
	given(tx.isActive()).willReturn(true);

	assertTrue(!TransactionSynchronizationManager.hasResource(factory));
	assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
	TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(manager));

	try {
		tt.execute(new TransactionCallback() {
			@Override
			public Object doInTransaction(TransactionStatus status) {
				assertTrue(TransactionSynchronizationManager.hasResource(factory));
				assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
				EntityManagerFactoryUtils.getTransactionalEntityManager(factory);
				status.setRollbackOnly();
				return null;
			}
		});

		assertTrue(TransactionSynchronizationManager.hasResource(factory));
		assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
	}
	finally {
		TransactionSynchronizationManager.unbindResource(factory);
	}

	verify(tx).begin();
	verify(tx).rollback();
	verify(manager).clear();
}
 
Example 10
Source File: JpaTransactionManagerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testTransactionCommitWithPreboundAndPropagationSupports() {
	final List<String> l = new ArrayList<>();
	l.add("test");

	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);

	assertTrue(!TransactionSynchronizationManager.hasResource(factory));
	assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
	TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(manager));

	try {
		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());
	}
	finally {
		TransactionSynchronizationManager.unbindResource(factory);
	}

	verify(manager).flush();
}
 
Example 11
Source File: DataSourceUtils.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void beforeCompletion() {
	// Release Connection early if the holder is not open anymore
	// (that is, not used by another resource like a Hibernate Session
	// that has its own cleanup via transaction synchronization),
	// to avoid issues with strict JTA implementations that expect
	// the close call before transaction completion.
	if (!this.connectionHolder.isOpen()) {
		TransactionSynchronizationManager.unbindResource(this.dataSource);
		this.holderActive = false;
		if (this.connectionHolder.hasConnection()) {
			releaseConnection(this.connectionHolder.getConnection(), this.dataSource);
		}
	}
}
 
Example 12
Source File: UserService1Test.java    From wetech-cms with MIT License 5 votes vote down vote up
@After
public void tearDown() throws SQLException, IOException {
	SessionHolder holder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
	Session s = holder.getSession(); 
	s.flush();
	TransactionSynchronizationManager.unbindResource(sessionFactory);
	//this.resumeTable();
}
 
Example 13
Source File: CciLocalTransactionManager.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected void doCleanupAfterCompletion(Object transaction) {
	CciLocalTransactionObject txObject = (CciLocalTransactionObject) transaction;
	ConnectionFactory connectionFactory = obtainConnectionFactory();

	// Remove the connection holder from the thread.
	TransactionSynchronizationManager.unbindResource(connectionFactory);
	txObject.getConnectionHolder().clear();

	Connection con = txObject.getConnectionHolder().getConnection();
	if (logger.isDebugEnabled()) {
		logger.debug("Releasing CCI Connection [" + con + "] after transaction");
	}
	ConnectionFactoryUtils.releaseConnection(con, connectionFactory);
}
 
Example 14
Source File: DataSourceUtils.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public void beforeCompletion() {
	// Release Connection early if the holder is not open anymore
	// (that is, not used by another resource like a Hibernate Session
	// that has its own cleanup via transaction synchronization),
	// to avoid issues with strict JTA implementations that expect
	// the close call before transaction completion.
	if (!this.connectionHolder.isOpen()) {
		TransactionSynchronizationManager.unbindResource(this.dataSource);
		this.holderActive = false;
		if (this.connectionHolder.hasConnection()) {
			releaseConnection(this.connectionHolder.getConnection(), this.dataSource);
		}
	}
}
 
Example 15
Source File: RoleDaoTest.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);
	this.resumeTable();
}
 
Example 16
Source File: OpenSessionInViewInterceptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Unbind the Hibernate {@code Session} from the thread and close it).
 * @see org.springframework.transaction.support.TransactionSynchronizationManager
 */
@Override
public void afterCompletion(WebRequest request, Exception ex) throws DataAccessException {
	if (!decrementParticipateCount(request)) {
		SessionHolder sessionHolder =
				(SessionHolder) TransactionSynchronizationManager.unbindResource(getSessionFactory());
		logger.debug("Closing Hibernate Session in OpenSessionInViewInterceptor");
		SessionFactoryUtils.closeSession(sessionHolder.getSession());
	}
}
 
Example 17
Source File: SpannerTransactionManagerTests.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Test
public void testDoBegin() {
	when(transactionManager.begin()).thenReturn(transactionContext);

	TransactionSynchronizationManager.unbindResource(this.databaseClient);

	TransactionDefinition definition = new DefaultTransactionDefinition();

	manager.doBegin(tx, definition);

	Assert.assertEquals(tx.getTransactionManager(), transactionManager);
	Assert.assertEquals(tx.getTransactionContext(), transactionContext);
	Assert.assertFalse(tx.isReadOnly());

	verify(transactionManager, times(1)).begin();
}
 
Example 18
Source File: DataSourceTransactionManager.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
protected Object doSuspend(Object transaction) {
	DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
	txObject.setConnectionHolder(null);
	return TransactionSynchronizationManager.unbindResource(obtainDataSource());
}
 
Example 19
Source File: AsyncRequestInterceptor.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) {
	TransactionSynchronizationManager.unbindResource(this.sessionFactory);
}
 
Example 20
Source File: OpenSessionInViewInterceptor.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
public void afterConcurrentHandlingStarted(WebRequest request) {
	if (!decrementParticipateCount(request)) {
		TransactionSynchronizationManager.unbindResource(obtainSessionFactory());
	}
}