List of usage examples for org.springframework.transaction.support TransactionSynchronizationManager getResource
@Nullable public static Object getResource(Object key)
From source file:org.mybatis.spring.SqlSessionUtils.java
/** * Gets an SqlSession from Spring Transaction Manager or creates a new one if needed. * Tries to get a SqlSession out of current transaction. If there is not any, it creates a new one. * Then, it synchronizes the SqlSession with the transaction if Spring TX is active and * <code>SpringManagedTransactionFactory</code> is configured as a transaction manager. * * @param sessionFactory a MyBatis {@code SqlSessionFactory} to create new sessions * @param executorType The executor type of the SqlSession to create * @param exceptionTranslator Optional. Translates SqlSession.commit() exceptions to Spring exceptions. * @throws TransientDataAccessResourceException if a transaction is active and the * {@code SqlSessionFactory} is not using a {@code SpringManagedTransactionFactory} * @see SpringManagedTransactionFactory//from w w w . j av a2 s. c o m */ public static SqlSession getSqlSession(SqlSessionFactory sessionFactory, ExecutorType executorType, PersistenceExceptionTranslator exceptionTranslator) { notNull(sessionFactory, NO_SQL_SESSION_FACTORY_SPECIFIED); notNull(executorType, NO_EXECUTOR_TYPE_SPECIFIED); SqlSessionHolder holder = (SqlSessionHolder) TransactionSynchronizationManager.getResource(sessionFactory); SqlSession session = sessionHolder(executorType, holder); if (session != null) { return session; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Creating a new SqlSession"); } session = sessionFactory.openSession(executorType); registerSessionHolder(sessionFactory, executorType, exceptionTranslator, session); return session; }
From source file:org.hengdao.utils.SqlSessionUtils.java
/** * If a Spring transaction is active it uses {@code DataSourceUtils} to get * a Spring managed {@code Connection}, then creates a new * {@code SqlSession} with this connection and synchronizes it with the * transaction. If there is not an active transaction it gets a connection * directly from the {@code DataSource} and creates a {@code SqlSession} * with it./*from w w w.j av a2 s . c o m*/ * * @param sessionFactory * a MyBatis {@code SqlSessionFactory} to create new sessions * @param executorType * The executor type of the SqlSession to create * @param exceptionTranslator * Optional. Translates SqlSession.commit() exceptions to Spring * exceptions. * @throws TransientDataAccessResourceException * if a transaction is active and the {@code SqlSessionFactory} * is not using a {@code SpringManagedTransactionFactory} * @see SpringManagedTransactionFactory */ public static SqlSession getSqlSession(SqlSessionFactory sessionFactory, ExecutorType executorType, PersistenceExceptionTranslator exceptionTranslator) { Assert.notNull(sessionFactory, "No SqlSessionFactory specified"); Assert.notNull(executorType, "No ExecutorType specified"); SqlSessionHolder holder = (SqlSessionHolder) TransactionSynchronizationManager.getResource(sessionFactory); if (holder != null && holder.isSynchronizedWithTransaction()) { if (holder.getExecutorType() != executorType) { throw new TransientDataAccessResourceException( "Cannot change the ExecutorType when there is an existing transaction"); } holder.requested(); if (logger.isDebugEnabled()) { logger.debug("Fetched SqlSession [" + holder.getSqlSession() + "] from current transaction"); } return holder.getSqlSession(); } DataSource dataSource = sessionFactory.getConfiguration().getEnvironment().getDataSource(); // SqlSessionFactoryBean unwraps TransactionAwareDataSourceProxies but // we keep this check for the case that SqlSessionUtils is called from // custom code boolean transactionAware = (dataSource instanceof TransactionAwareDataSourceProxy); Connection conn; try { conn = transactionAware ? dataSource.getConnection() : DataSourceUtils.getConnection(dataSource); } catch (SQLException e) { throw new CannotGetJdbcConnectionException("Could not get JDBC Connection for SqlSession", e); } if (logger.isDebugEnabled()) { logger.debug("Creating SqlSession with JDBC Connection [" + conn + "]"); } // Assume either DataSourceTransactionManager or the underlying // connection pool already dealt with enabling auto commit. // This may not be a good assumption, but the overhead of checking // connection.getAutoCommit() again may be expensive (?) in some drivers // (see DataSourceTransactionManager.doBegin()). One option would be to // only check for auto commit if this function is being called outside // of DSTxMgr, but to do that we would need to be able to call // ConnectionHolder.isTransactionActive(), which is protected and not // visible to this class. SqlSession session = sessionFactory.openSession(executorType, conn); // Register session holder and bind it to enable synchronization. // // Note: The DataSource should be synchronized with the transaction // either through DataSourceTxMgr or another tx synchronization. // Further assume that if an exception is thrown, whatever started the // transaction will // handle closing / rolling back the Connection associated with the // SqlSession. if (TransactionSynchronizationManager.isSynchronizationActive()) { if (!(sessionFactory.getConfiguration().getEnvironment() .getTransactionFactory() instanceof SpringManagedTransactionFactory) && DataSourceUtils.isConnectionTransactional(conn, dataSource)) { throw new TransientDataAccessResourceException( "SqlSessionFactory must be using a SpringManagedTransactionFactory in order to use Spring transaction synchronization"); } if (logger.isDebugEnabled()) { logger.debug("Registering transaction synchronization for SqlSession [" + session + "]"); } holder = new SqlSessionHolder(session, executorType, exceptionTranslator); TransactionSynchronizationManager.bindResource(sessionFactory, holder); TransactionSynchronizationManager .registerSynchronization(new SqlSessionSynchronization(holder, sessionFactory)); holder.setSynchronizedWithTransaction(true); holder.requested(); } else { if (logger.isDebugEnabled()) { logger.debug("SqlSession [" + session + "] was not registered for synchronization because synchronization is not active"); } } return session; }
From source file:org.inbio.m3s.service.AbstractServiceTest.java
/** * One time teardown which closes the session opened for the tests. *//* w ww . j a va 2 s . co m*/ protected void onTearDown() throws Exception { //logger.trace("onTearDown(): entered method."); super.onTearDown(); SessionFactory sessionFactory = (SessionFactory) getBean("sessionFactory"); SessionHolder holder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory); Session session = holder.getSession(); if (session.isOpen()) { if (session.isDirty()) { session.flush(); } session.close(); } if (session.isConnected()) { session.connection().close(); } holder.removeSession(session); TransactionSynchronizationManager.unbindResource(sessionFactory); }
From source file:org.mybatis.spring.SqlSessionTemplateTest.java
@Test public void testExecutorType() { SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory, ExecutorType.BATCH); assertEquals(ExecutorType.BATCH, template.getExecutorType()); DataSourceTransactionManager manager = new DataSourceTransactionManager(dataSource); TransactionStatus status = null;/* ww w .j av a 2 s . c o m*/ try { status = manager.getTransaction(new DefaultTransactionDefinition()); // will synchronize the template with the current tx template.getConnection(); SqlSessionHolder holder = (SqlSessionHolder) TransactionSynchronizationManager .getResource(sqlSessionFactory); assertEquals(ExecutorType.BATCH, holder.getExecutorType()); } finally { // rollback required to close connection txManager.rollback(status); } }
From source file:org.openvpms.component.business.dao.hibernate.im.common.Context.java
/** * Returns the context for the given assembler and session and current * thread.//w w w .j a va2 s .c o m * <p/> * If one does not exist, it will be created. * * @param assembler the assembler * @param session the hibernate session * @return the context */ public static Context getContext(Assembler assembler, Session session) { Context context; ResourceKey key = new ResourceKey(session); if (TransactionSynchronizationManager.isSynchronizationActive()) { if (!TransactionSynchronizationManager.hasResource(key)) { context = new Context(assembler, session, true); TransactionSynchronizationManager.bindResource(context.getResourceKey(), context); TransactionSynchronizationManager.registerSynchronization(new ContextSynchronization(context)); } else { context = (Context) TransactionSynchronizationManager.getResource(key); } } else { context = new Context(assembler, session, false); } return context; }
From source file:org.drools.container.spring.beans.persistence.DroolsSpringJpaManager.java
public void beginCommandScopedEntityManager() { EntityManager cmdScopedEntityManager = (EntityManager) env.get(EnvironmentName.CMD_SCOPED_ENTITY_MANAGER); if (cmdScopedEntityManager == null || !cmdScopedEntityManager.isOpen()) { EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager .getResource("cmdEM"); EntityManager em = null;//from w w w. j ava 2 s . c om if (emHolder == null) { em = this.emf.createEntityManager(); emHolder = new EntityManagerHolder(em); TransactionSynchronizationManager.bindResource("cmdEM", emHolder); } else { em = emHolder.getEntityManager(); } this.env.set(EnvironmentName.CMD_SCOPED_ENTITY_MANAGER, em); } this.getCommandScopedPersistenceContext().joinTransaction(); this.appScopedEntityManager.joinTransaction(); }
From source file:org.dalesbred.integration.spring.SpringTransactionManager.java
@Override public boolean hasActiveTransaction() { ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource); return conHolder != null && (conHolder.getConnectionHandle() != null || conHolder.isSynchronizedWithTransaction()); }
From source file:com.mobileman.projecth.TestCaseBase.java
/** * @throws Exception/*from w w w . j a va 2s. c o m*/ */ @After public void tearDown() throws Exception { if (sessionOwner && session != null) { SessionHolder holder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory); Session s = holder.getSession(); s.flush(); TransactionSynchronizationManager.unbindResource(sessionFactory); SessionFactoryUtils.closeSession(s); } if (wiser != null) { wiser.stop(); } }
From source file:org.cfr.capsicum.datasource.DataSourceUtils.java
/** * Actually obtain a JDBC Connection from the given DataSource. * Same as {@link #getConnection}, but throwing the original SQLException. * <p>Is aware of a corresponding Connection bound to the current thread, for example * when using {@link DataSourceTransactionManager}. Will bind a Connection to the thread * if transaction synchronization is active (e.g. if in a JTA transaction). * <p>Directly accessed by {@link TransactionAwareDataSourceProxy}. * @param dataSource the DataSource to obtain Connections from * @return a JDBC Connection from the given DataSource * @throws SQLException if thrown by JDBC methods * @see #doReleaseConnection/*w w w.j av a 2 s .c o m*/ */ public static Connection doGetConnection(DataSource dataSource) throws SQLException { Assert.notNull(dataSource, "No DataSource specified"); CayenneConnectionHolder conHolder = (CayenneConnectionHolder) TransactionSynchronizationManager .getResource(dataSource); if (conHolder != null && (conHolder.hasConnection() || conHolder.isSynchronizedWithTransaction())) { conHolder.requested(); if (!conHolder.hasConnection()) { logger.debug("Fetching resumed JDBC Connection from DataSource"); conHolder.setConnection(dataSource.getConnection()); } return conHolder.getConnection(); } // Else we either got no holder or an empty thread-bound holder here. logger.debug("Fetching JDBC Connection from DataSource"); Connection con = dataSource.getConnection(); if (TransactionSynchronizationManager.isSynchronizationActive()) { logger.debug("Registering transaction synchronization for JDBC Connection"); // Use same Connection for further JDBC actions within the transaction. // Thread-bound object will get removed by synchronization at transaction completion. CayenneConnectionHolder holderToUse = conHolder; if (holderToUse == null) { ObjectContext context = BaseContext.getThreadObjectContext(); holderToUse = new CayenneConnectionHolder(con, context); } else { holderToUse.setConnection(con); } holderToUse.requested(); TransactionSynchronizationManager .registerSynchronization(new ConnectionSynchronization(holderToUse, dataSource)); holderToUse.setSynchronizedWithTransaction(true); if (holderToUse != conHolder) { TransactionSynchronizationManager.bindResource(dataSource, holderToUse); } } return con; }