Java Code Examples for org.springframework.transaction.support.TransactionSynchronizationManager#bindResource()
The following examples show how to use
org.springframework.transaction.support.TransactionSynchronizationManager#bindResource() .
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: HibernateInterceptorTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void testInterceptorWithThreadBoundEmptyHolder() { SessionHolder holder = new SessionHolder("key", session); holder.removeSession("key"); TransactionSynchronizationManager.bindResource(sessionFactory, holder); HibernateInterceptor interceptor = new HibernateInterceptor(); interceptor.setSessionFactory(sessionFactory); try { interceptor.invoke(invocation); } catch (Throwable t) { fail("Should not have thrown Throwable: " + t.getMessage()); } verify(session).flush(); verify(session).close(); }
Example 2
Source File: HibernateInterceptorTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void testInterceptorWithThreadBoundAndFlushAlways() { given(session.isOpen()).willReturn(true); given(session.getFlushMode()).willReturn(FlushMode.AUTO); TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); HibernateInterceptor interceptor = new HibernateInterceptor(); interceptor.setSessionFactory(sessionFactory); interceptor.setFlushMode(HibernateInterceptor.FLUSH_ALWAYS); 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.ALWAYS); ordered.verify(session).setFlushMode(FlushMode.AUTO); verify(session, never()).flush(); }
Example 3
Source File: RedissonTransactionManager.java From redisson with Apache License 2.0 | 6 votes |
@Override protected void doBegin(Object transaction, TransactionDefinition definition) throws TransactionException { RedissonTransactionObject tObject = (RedissonTransactionObject) transaction; if (tObject.getTransactionHolder() == null) { int timeout = determineTimeout(definition); TransactionOptions options = TransactionOptions.defaults(); if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) { options.timeout(timeout, TimeUnit.SECONDS); } RTransaction trans = redisson.createTransaction(options); RedissonTransactionHolder holder = new RedissonTransactionHolder(); holder.setTransaction(trans); tObject.setTransactionHolder(holder); TransactionSynchronizationManager.bindResource(redisson, holder); } }
Example 4
Source File: HibernateInterceptorTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void testInterceptorWithThreadBoundAndFilter() { given(session.isOpen()).willReturn(true); TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); HibernateInterceptor interceptor = new HibernateInterceptor(); interceptor.setSessionFactory(sessionFactory); interceptor.setFilterName("myFilter"); 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).enableFilter("myFilter"); ordered.verify(session).disableFilter("myFilter"); }
Example 5
Source File: SpringTransactionManager.java From ignite with Apache License 2.0 | 5 votes |
/** {@inheritDoc} */ @Override protected void doBegin(Object transaction, TransactionDefinition definition) throws TransactionException { if (definition.getIsolationLevel() == TransactionDefinition.ISOLATION_READ_UNCOMMITTED) throw new InvalidIsolationLevelException("Ignite does not support READ_UNCOMMITTED isolation level."); IgniteTransactionObject txObj = (IgniteTransactionObject)transaction; Transaction tx = null; try { if (txObj.getTransactionHolder() == null || txObj.getTransactionHolder().isSynchronizedWithTransaction()) { long timeout = ignite.configuration().getTransactionConfiguration().getDefaultTxTimeout(); if (definition.getTimeout() > 0) timeout = TimeUnit.SECONDS.toMillis(definition.getTimeout()); Transaction newTx = ignite.transactions().txStart(transactionConcurrency, convertToIgniteIsolationLevel(definition.getIsolationLevel()), timeout, 0); if (log.isDebugEnabled()) log.debug("Started Ignite transaction: " + newTx); txObj.setTransactionHolder(new IgniteTransactionHolder(newTx), true); } txObj.getTransactionHolder().setSynchronizedWithTransaction(true); txObj.getTransactionHolder().setTransactionActive(true); tx = txObj.getTransactionHolder().getTransaction(); // Bind the session holder to the thread. if (txObj.isNewTransactionHolder()) TransactionSynchronizationManager.bindResource(this.ignite, txObj.getTransactionHolder()); } catch (Exception ex) { if (tx != null) tx.close(); throw new CannotCreateTransactionException("Could not create Ignite transaction", ex); } }
Example 6
Source File: JpaTransactionManagerTests.java From spring-analysis-note with MIT License | 5 votes |
@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 7
Source File: OpenEntityManagerInViewInterceptor.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public void preHandle(WebRequest request) throws DataAccessException { String participateAttributeName = getParticipateAttributeName(); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); if (asyncManager.hasConcurrentResult()) { if (applyCallableInterceptor(asyncManager, participateAttributeName)) { return; } } if (TransactionSynchronizationManager.hasResource(getEntityManagerFactory())) { // Do not modify the EntityManager: just mark the request accordingly. Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST); int newCount = (count != null ? count + 1 : 1); request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST); } else { logger.debug("Opening JPA EntityManager in OpenEntityManagerInViewInterceptor"); try { EntityManager em = createEntityManager(); EntityManagerHolder emHolder = new EntityManagerHolder(em); TransactionSynchronizationManager.bindResource(getEntityManagerFactory(), emHolder); AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(getEntityManagerFactory(), emHolder); asyncManager.registerCallableInterceptor(participateAttributeName, interceptor); asyncManager.registerDeferredResultInterceptor(participateAttributeName, interceptor); } catch (PersistenceException ex) { throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex); } } }
Example 8
Source File: HibernateTransactionManager.java From spring4-understanding with Apache License 2.0 | 5 votes |
@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 9
Source File: OpenPersistenceManagerInViewFilter.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { PersistenceManagerFactory pmf = lookupPersistenceManagerFactory(request); boolean participate = false; if (TransactionSynchronizationManager.hasResource(pmf)) { // Do not modify the PersistenceManager: just set the participate flag. participate = true; } else { logger.debug("Opening JDO PersistenceManager in OpenPersistenceManagerInViewFilter"); PersistenceManager pm = PersistenceManagerFactoryUtils.getPersistenceManager(pmf, true); TransactionSynchronizationManager.bindResource(pmf, new PersistenceManagerHolder(pm)); } try { filterChain.doFilter(request, response); } finally { if (!participate) { PersistenceManagerHolder pmHolder = (PersistenceManagerHolder) TransactionSynchronizationManager.unbindResource(pmf); logger.debug("Closing JDO PersistenceManager in OpenPersistenceManagerInViewFilter"); PersistenceManagerFactoryUtils.releasePersistenceManager(pmHolder.getPersistenceManager(), pmf); } } }
Example 10
Source File: ExtendedEntityManagerCreator.java From spring-analysis-note with MIT License | 5 votes |
/** * Enlist this application-managed EntityManager in the current transaction. */ private void enlistInCurrentTransaction() { // Resource local transaction, need to acquire the EntityTransaction, // start a transaction now and enlist a synchronization for commit or rollback later. EntityTransaction et = this.target.getTransaction(); et.begin(); if (logger.isDebugEnabled()) { logger.debug("Starting resource-local transaction on application-managed " + "EntityManager [" + this.target + "]"); } ExtendedEntityManagerSynchronization extendedEntityManagerSynchronization = new ExtendedEntityManagerSynchronization(this.target, this.exceptionTranslator); TransactionSynchronizationManager.bindResource(this.target, extendedEntityManagerSynchronization); TransactionSynchronizationManager.registerSynchronization(extendedEntityManagerSynchronization); }
Example 11
Source File: OpenEntityManagerInViewInterceptor.java From java-technology-stack with MIT License | 5 votes |
@Override public void preHandle(WebRequest request) throws DataAccessException { String key = getParticipateAttributeName(); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); if (asyncManager.hasConcurrentResult() && applyEntityManagerBindingInterceptor(asyncManager, key)) { return; } EntityManagerFactory emf = obtainEntityManagerFactory(); if (TransactionSynchronizationManager.hasResource(emf)) { // Do not modify the EntityManager: just mark the request accordingly. Integer count = (Integer) request.getAttribute(key, WebRequest.SCOPE_REQUEST); int newCount = (count != null ? count + 1 : 1); request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST); } else { logger.debug("Opening JPA EntityManager in OpenEntityManagerInViewInterceptor"); try { EntityManager em = createEntityManager(); EntityManagerHolder emHolder = new EntityManagerHolder(em); TransactionSynchronizationManager.bindResource(emf, emHolder); AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(emf, emHolder); asyncManager.registerCallableInterceptor(key, interceptor); asyncManager.registerDeferredResultInterceptor(key, interceptor); } catch (PersistenceException ex) { throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex); } } }
Example 12
Source File: OpenSessionInViewInterceptor.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Open a new Hibernate {@code Session} according to the settings of this * {@code HibernateAccessor} and bind it to the thread via the * {@link TransactionSynchronizationManager}. * @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession */ @Override public void preHandle(WebRequest request) throws DataAccessException { String participateAttributeName = getParticipateAttributeName(); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); if (asyncManager.hasConcurrentResult()) { if (applySessionBindingInterceptor(asyncManager, participateAttributeName)) { return; } } if ((isSingleSession() && TransactionSynchronizationManager.hasResource(getSessionFactory())) || org.springframework.orm.hibernate3.SessionFactoryUtils.isDeferredCloseActive(getSessionFactory())) { // Do not modify the Session: just mark the request accordingly. Integer count = (Integer) request.getAttribute(participateAttributeName, WebRequest.SCOPE_REQUEST); int newCount = (count != null ? count + 1 : 1); request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST); } else { if (isSingleSession()) { // single session mode logger.debug("Opening single Hibernate Session in OpenSessionInViewInterceptor"); Session session = org.springframework.orm.hibernate3.SessionFactoryUtils.getSession( getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator()); applyFlushMode(session, false); org.springframework.orm.hibernate3.SessionHolder sessionHolder = new org.springframework.orm.hibernate3.SessionHolder(session); TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder); AsyncRequestInterceptor asyncRequestInterceptor = new AsyncRequestInterceptor(getSessionFactory(), sessionHolder); asyncManager.registerCallableInterceptor(participateAttributeName, asyncRequestInterceptor); asyncManager.registerDeferredResultInterceptor(participateAttributeName, asyncRequestInterceptor); } else { // deferred close mode org.springframework.orm.hibernate3.SessionFactoryUtils.initDeferredClose(getSessionFactory()); } } }
Example 13
Source File: JpaTransactionManagerHandlerTest.java From opensharding-spi-impl with Apache License 2.0 | 5 votes |
@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 14
Source File: HibernateTransactionManager.java From java-technology-stack with MIT License | 5 votes |
@Override protected void doResume(@Nullable Object transaction, Object suspendedResources) { SessionFactory sessionFactory = obtainSessionFactory(); SuspendedResourcesHolder resourcesHolder = (SuspendedResourcesHolder) suspendedResources; if (TransactionSynchronizationManager.hasResource(sessionFactory)) { // From non-transactional code running in active transaction synchronization // -> can be safely removed, will be closed on transaction completion. TransactionSynchronizationManager.unbindResource(sessionFactory); } TransactionSynchronizationManager.bindResource(sessionFactory, resourcesHolder.getSessionHolder()); if (getDataSource() != null && resourcesHolder.getConnectionHolder() != null) { TransactionSynchronizationManager.bindResource(getDataSource(), resourcesHolder.getConnectionHolder()); } }
Example 15
Source File: IndexPicDaoTest.java From wetech-cms with MIT License | 4 votes |
@Before public void setUp() throws SQLException, IOException, DatabaseUnitException { //此时最好不要使用Spring的Transactional来管理,因为dbunit是通过jdbc来处理connection,再使用spring在一些编辑操作中会造成事务shisu Session s = sessionFactory.openSession(); TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(s)); }
Example 16
Source File: AsyncRequestInterceptor.java From spring-analysis-note with MIT License | 4 votes |
public void bindSession() { this.timeoutInProgress = false; this.errorInProgress = false; TransactionSynchronizationManager.bindResource(this.sessionFactory, this.sessionHolder); }
Example 17
Source File: UserDaoTest.java From wetech-cms with MIT License | 4 votes |
@Before public void setUp() throws DataSetException, SQLException, IOException { Session s = sessionFactory.openSession(); TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(s)); this.backupAllTable(); }
Example 18
Source File: SpringSessionSynchronization.java From spring4-understanding with Apache License 2.0 | 4 votes |
@Override public void resume() { if (this.holderActive) { TransactionSynchronizationManager.bindResource(this.sessionFactory, this.sessionHolder); } }
Example 19
Source File: SpringSessionSynchronization.java From lams with GNU General Public License v2.0 | 4 votes |
@Override public void resume() { if (this.holderActive) { TransactionSynchronizationManager.bindResource(this.sessionFactory, this.sessionHolder); } }
Example 20
Source File: DataSourceTransactionManager.java From java-technology-stack with MIT License | 4 votes |
@Override protected void doResume(@Nullable Object transaction, Object suspendedResources) { TransactionSynchronizationManager.bindResource(obtainDataSource(), suspendedResources); }