Java Code Examples for org.springframework.transaction.support.TransactionSynchronizationManager#isSynchronizationActive()
The following examples show how to use
org.springframework.transaction.support.TransactionSynchronizationManager#isSynchronizationActive() .
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: ContextSourceAndHibernateTransactionManagerIntegrationTest.java From spring-ldap with Apache License 2.0 | 7 votes |
@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 2
Source File: ConnectionFactoryUtils.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Actually obtain a CCI Connection from the given ConnectionFactory. * Same as {@link #getConnection}, but throwing the original ResourceException. * <p>Is aware of a corresponding Connection bound to the current thread, for example * when using {@link CciLocalTransactionManager}. Will bind a Connection to the thread * if transaction synchronization is active (e.g. if in a JTA transaction). * <p>Directly accessed by {@link TransactionAwareConnectionFactoryProxy}. * @param cf the ConnectionFactory to obtain Connection from * @return a CCI Connection from the given ConnectionFactory * @throws ResourceException if thrown by CCI API methods * @see #doReleaseConnection */ public static Connection doGetConnection(ConnectionFactory cf) throws ResourceException { Assert.notNull(cf, "No ConnectionFactory specified"); ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(cf); if (conHolder != null) { return conHolder.getConnection(); } logger.debug("Opening CCI Connection"); Connection con = cf.getConnection(); if (TransactionSynchronizationManager.isSynchronizationActive()) { logger.debug("Registering transaction synchronization for CCI Connection"); conHolder = new ConnectionHolder(con); conHolder.setSynchronizedWithTransaction(true); TransactionSynchronizationManager.registerSynchronization(new ConnectionSynchronization(conHolder, cf)); TransactionSynchronizationManager.bindResource(cf, conHolder); } return con; }
Example 3
Source File: AbstractLuceneIndexerAndSearcherFactory.java From alfresco-repository with GNU Lesser General Public License v3.0 | 6 votes |
/** * Get the transaction identifier used to store it in the transaction map. * * @param tx Transaction * @param storeRef StoreRef * @return - the transaction id */ @SuppressWarnings("unchecked") private String getTransactionId(Transaction tx, StoreRef storeRef) { if (tx instanceof SimpleTransaction) { SimpleTransaction simpleTx = (SimpleTransaction) tx; return simpleTx.getGUID(); } else if (TransactionSynchronizationManager.isSynchronizationActive()) { Map<StoreRef, LuceneIndexer> indexers = (Map<StoreRef, LuceneIndexer>) AlfrescoTransactionSupport.getResource(indexersKey); if (indexers != null) { LuceneIndexer indexer = indexers.get(storeRef); if (indexer != null) { return indexer.getDeltaId(); } } } return null; }
Example 4
Source File: ApplicationListenerMethodTransactionalAdapter.java From lams with GNU General Public License v2.0 | 6 votes |
@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 5
Source File: AbstractSolrQuery.java From dubbox with Apache License 2.0 | 6 votes |
@Override public Object execute(Query query) { if (TransactionSynchronizationManager.isSynchronizationActive()) { SolrTransactionSynchronizationAdapterBuilder.forOperations(solrOperations).withDefaultBehaviour() .register(); } Object result = countOrGetDocumentsForDelete(query); solrOperations.delete(query); if (!TransactionSynchronizationManager.isSynchronizationActive()) { solrOperations.commit(); } return result; }
Example 6
Source File: HibernatePersistenceContextInterceptor.java From gorm-hibernate5 with Apache License 2.0 | 5 votes |
public void flush() { if (getSessionFactory() == null) return; if(!getParticipate()) { if(!transactionRequired) { getSession().flush(); } else if(TransactionSynchronizationManager.isSynchronizationActive()) { getSession().flush(); } } }
Example 7
Source File: ExtendedEntityManagerCreator.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * Join an existing transaction, if not already joined. * @param enforce whether to enforce the transaction * (i.e. whether failure to join is considered fatal) */ private void doJoinTransaction(boolean enforce) { if (this.jta) { // Let's try whether we're in a JTA transaction. try { this.target.joinTransaction(); logger.debug("Joined JTA transaction"); } catch (TransactionRequiredException ex) { if (!enforce) { logger.debug("No JTA transaction to join: " + ex); } else { throw ex; } } } else { if (TransactionSynchronizationManager.isSynchronizationActive()) { if (!TransactionSynchronizationManager.hasResource(this.target) && !this.target.getTransaction().isActive()) { enlistInCurrentTransaction(); } logger.debug("Joined local transaction"); } else { if (!enforce) { logger.debug("No local transaction to join"); } else { throw new TransactionRequiredException("No local transaction to join"); } } } }
Example 8
Source File: SpringTransactionProvider.java From qmq with Apache License 2.0 | 5 votes |
@Override public void setTransactionListener(TransactionListener listener) { if (!TransactionSynchronizationManager.isSynchronizationActive()) throw E; this.transactionListener = listener; TransactionSynchronizationManager.registerSynchronization(this); }
Example 9
Source File: TransactionAwareCacheDecorator.java From java-technology-stack with MIT License | 5 votes |
@Override public void clear() { if (TransactionSynchronizationManager.isSynchronizationActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { targetCache.clear(); } }); } else { this.targetCache.clear(); } }
Example 10
Source File: TransactionAwareSessionContext.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Registers transaction synchronization with session in order to clean up and close the session when transaction * finishes. * * @param session * Session to register into transaction synchronization. Cannot be null. * @return Returns <code>true</code> if the session was register into any available synchronization strategy, * <code>false</code> otherwise. */ private boolean registerSynchronization(final Session session) { // Tries Spring's transaction manager synchronization. if (TransactionSynchronizationManager.isSynchronizationActive()) { // If it's allowed, registers synchronization to cleanup session. TransactionSynchronizationManager.registerSynchronization(createTransactionSynchronization(session)); return true; } else { // Tries JTA transaction manager synchronization. JtaPlatform jtaPlatform = sessionFactory.getServiceRegistry().getService(JtaPlatform.class); // If it's allowed, registers synchronization to cleanup session. if (jtaPlatform.canRegisterSynchronization()) { List<TransactionSynchronization> synchronizations; synchronizations = Arrays.asList(createTransactionSynchronization(session)); Synchronization jtaSync; jtaSync = new JtaAfterCompletionSynchronization(synchronizations); jtaPlatform.registerSynchronization(jtaSync); return true; } } return false; }
Example 11
Source File: TransactionalRepositoryDecorator.java From molgenis with GNU Lesser General Public License v3.0 | 5 votes |
@SuppressWarnings("ConstantConditions") @Override public long count() { if (TransactionSynchronizationManager.isSynchronizationActive()) { return delegate().count(); } else { return createReadonlyTransactionTemplate().execute(status -> delegate().count()); } }
Example 12
Source File: TransactionalRepositoryDecorator.java From molgenis with GNU Lesser General Public License v3.0 | 5 votes |
@Override public E findOne(Query<E> q) { if (TransactionSynchronizationManager.isSynchronizationActive()) { return delegate().findOne(q); } else { return createReadonlyTransactionTemplate().execute(status -> delegate().findOne(q)); } }
Example 13
Source File: AbstractDatabaseInitializationTests.java From spring-analysis-note with MIT License | 5 votes |
@After public void shutDown() { if (TransactionSynchronizationManager.isSynchronizationActive()) { TransactionSynchronizationManager.clear(); TransactionSynchronizationManager.unbindResource(db); } db.shutdown(); }
Example 14
Source File: TransactionalRepositoryDecorator.java From molgenis with GNU Lesser General Public License v3.0 | 5 votes |
@Override public Stream<E> findAll(Stream<Object> ids, Fetch fetch) { if (TransactionSynchronizationManager.isSynchronizationActive()) { return delegate().findAll(ids, fetch); } else { return createReadonlyTransactionTemplate().execute(status -> delegate().findAll(ids, fetch)); } }
Example 15
Source File: ContextSourceTransactionManagerIntegrationTest.java From spring-ldap with Apache License 2.0 | 4 votes |
@Before public void prepareTestedInstance() throws Exception { if (TransactionSynchronizationManager.isSynchronizationActive()) { TransactionSynchronizationManager.clearSynchronization(); } }
Example 16
Source File: DataSourceUtils.java From spring-analysis-note with MIT License | 4 votes |
/** * 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 */ public static Connection doGetConnection(DataSource dataSource) throws SQLException { Assert.notNull(dataSource, "No DataSource specified"); ConnectionHolder conHolder = (ConnectionHolder) 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(fetchConnection(dataSource)); } 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 = fetchConnection(dataSource); if (TransactionSynchronizationManager.isSynchronizationActive()) { try { // Use same Connection for further JDBC actions within the transaction. // Thread-bound object will get removed by synchronization at transaction completion. ConnectionHolder holderToUse = conHolder; if (holderToUse == null) { holderToUse = new ConnectionHolder(con); } else { holderToUse.setConnection(con); } holderToUse.requested(); TransactionSynchronizationManager.registerSynchronization( new ConnectionSynchronization(holderToUse, dataSource)); holderToUse.setSynchronizedWithTransaction(true); if (holderToUse != conHolder) { TransactionSynchronizationManager.bindResource(dataSource, holderToUse); } } catch (RuntimeException ex) { // Unexpected exception from external delegation call -> close Connection and rethrow. releaseConnection(con, dataSource); throw ex; } } return con; }
Example 17
Source File: JtaUtil.java From iaf with Apache License 2.0 | 4 votes |
public static String displayTransactionStatus(TransactionStatus txStatus) { String result; result="txName ["+TransactionSynchronizationManager.getCurrentTransactionName()+"]"; if (txStatus!=null) { result+=" status new ["+txStatus.isNewTransaction()+"]"; result+=" status completeted ["+txStatus.isCompleted()+"]"; result+=" status rollbackOnly ["+txStatus.isRollbackOnly()+"]"; result+=" status hasSavepoint ["+txStatus.hasSavepoint()+"]"; } else { result+=" currently not in a transaction"; } result+=" isolation ["+TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()+"]"; result+=" active ["+TransactionSynchronizationManager.isActualTransactionActive()+"]"; boolean syncActive=TransactionSynchronizationManager.isSynchronizationActive(); result+=" synchronization active ["+syncActive+"]"; result+="\n"; Map<Object, Object> resources = TransactionSynchronizationManager.getResourceMap(); result += "resources:\n"; if (resources==null) { result+=" map is null\n"; } else { for (Iterator<Object> it=resources.keySet().iterator(); it.hasNext();) { Object key = it.next(); Object resource = resources.get(key); result += ClassUtils.nameOf(key)+"("+key+"): "+ClassUtils.nameOf(resource)+"("+resource+")\n"; if (resource instanceof JmsResourceHolder) { JmsResourceHolder jrh = (JmsResourceHolder)resource; result+=" connection: "+jrh.getConnection()+", session: "+jrh.getSession()+"\n"; } } } if (syncActive) { List<TransactionSynchronization> synchronizations = TransactionSynchronizationManager.getSynchronizations(); result += "synchronizations:\n"; for (int i=0; i<synchronizations.size(); i++) { TransactionSynchronization synchronization = synchronizations.get(i); result += ClassUtils.nameOf(synchronization)+"("+synchronization+")\n"; } } return result; }
Example 18
Source File: DistributedCacheManagerDecorator.java From rice with Educational Community License v2.0 | 2 votes |
/** * Should a transaction bound flush be performed? * @return true for transaction based flushing */ private boolean doTransactionalFlush() { return TransactionSynchronizationManager.isSynchronizationActive() && TransactionSynchronizationManager.isActualTransactionActive(); }
Example 19
Source File: TransactionAwareDataSourceProxy.java From spring-analysis-note with MIT License | 2 votes |
/** * Determine whether to obtain a fixed target Connection for the proxy * or to reobtain the target Connection for each operation. * <p>The default implementation returns {@code true} for all * standard cases. This can be overridden through the * {@link #setReobtainTransactionalConnections "reobtainTransactionalConnections"} * flag, which enforces a non-fixed target Connection within an active transaction. * Note that non-transactional access will always use a fixed Connection. * @param targetDataSource the target DataSource */ protected boolean shouldObtainFixedConnection(DataSource targetDataSource) { return (!TransactionSynchronizationManager.isSynchronizationActive() || !this.reobtainTransactionalConnections); }
Example 20
Source File: TransactionAwareDataSourceProxy.java From lams with GNU General Public License v2.0 | 2 votes |
/** * Determine whether to obtain a fixed target Connection for the proxy * or to reobtain the target Connection for each operation. * <p>The default implementation returns {@code true} for all * standard cases. This can be overridden through the * {@link #setReobtainTransactionalConnections "reobtainTransactionalConnections"} * flag, which enforces a non-fixed target Connection within an active transaction. * Note that non-transactional access will always use a fixed Connection. * @param targetDataSource the target DataSource */ protected boolean shouldObtainFixedConnection(DataSource targetDataSource) { return (!TransactionSynchronizationManager.isSynchronizationActive() || !this.reobtainTransactionalConnections); }