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

The following examples show how to use org.springframework.transaction.support.TransactionSynchronizationManager#getResource() . 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: OpenSessionInViewInterceptor.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Flush the Hibernate {@code Session} before view rendering, if necessary.
 * <p>Note that this just applies in {@link #isSingleSession() single session mode}!
 * <p>The default is {@code FLUSH_NEVER} to avoid this extra flushing,
 * assuming that service layer transactions have flushed their changes on commit.
 * @see #setFlushMode
 */
@Override
public void postHandle(WebRequest request, ModelMap model) throws DataAccessException {
	if (isSingleSession()) {
		// Only potentially flush in single session mode.
		SessionHolder sessionHolder =
				(SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory());
		logger.debug("Flushing single Hibernate Session in OpenSessionInViewInterceptor");
		try {
			flushIfNecessary(sessionHolder.getSession(), false);
		}
		catch (HibernateException ex) {
			throw convertHibernateAccessException(ex);
		}
	}
}
 
Example 2
Source File: CompensatingTransactionUtils.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
/**
 * Perform the specified operation, storing the state prior to the operation
 * in order to enable commit/rollback later. If no transaction is currently
 * active, proceed with the original call on the target.
 * 
 * @param synchronizationKey
 *            the transaction synchronization key we are operating on
 *            (typically something similar to a DataSource).
 * @param target
 *            the actual target resource that should be used for invoking
 *            the operation on should no transaction be active.
 * @param method
 *            name of the method to be invoked.
 * @param args
 *            arguments with which the operation is invoked.
 */
public static void performOperation(Object synchronizationKey,
        Object target, Method method, Object[] args) throws Throwable {
    CompensatingTransactionHolderSupport transactionResourceHolder = (CompensatingTransactionHolderSupport) TransactionSynchronizationManager
            .getResource(synchronizationKey);
    if (transactionResourceHolder != null) {

        CompensatingTransactionOperationManager transactionOperationManager = transactionResourceHolder
                .getTransactionOperationManager();
        transactionOperationManager.performOperation(
                transactionResourceHolder.getTransactedResource(), method
                        .getName(), args);
    } else {
        // Perform the target operation
        try {
            method.invoke(target, args);
        } catch (InvocationTargetException e) {
            throw e.getTargetException();
        }
    }
}
 
Example 3
Source File: ConnectionFactoryUtils.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 4
Source File: HibernateTemplate.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Prepare the given Criteria object, applying cache settings and/or
 * a transaction timeout.
 * @param criteria the Criteria object to prepare
 * @see #setCacheQueries
 * @see #setQueryCacheRegion
 */
protected void prepareCriteria(Criteria criteria) {
	if (isCacheQueries()) {
		criteria.setCacheable(true);
		if (getQueryCacheRegion() != null) {
			criteria.setCacheRegion(getQueryCacheRegion());
		}
	}
	if (getFetchSize() > 0) {
		criteria.setFetchSize(getFetchSize());
	}
	if (getMaxResults() > 0) {
		criteria.setMaxResults(getMaxResults());
	}

	SessionHolder sessionHolder =
			(SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory());
	if (sessionHolder != null && sessionHolder.hasTimeout()) {
		criteria.setTimeout(sessionHolder.getTimeToLiveInSeconds());
	}
}
 
Example 5
Source File: DataSourceUtils.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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(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.
		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);
		}
	}

	return con;
}
 
Example 6
Source File: SessionFactoryUtils.java    From mycollab with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Get a JCR Session for the given Repository. Is aware of and will return any existing corresponding
 * Session bound to the current thread, for example when using JcrTransactionManager. Same as
 * <code>getSession</code> but throws the original Repository.
 * @param sessionFactory Jcr Repository to create session with
 * @param allowCreate if a non-transactional Session should be created when no transactional Session can
 *            be found for the current thread
 * @throws RepositoryException
 * @return
 */
public static Session doGetSession(SessionFactory sessionFactory, boolean allowCreate) throws RepositoryException {
    Assert.notNull(sessionFactory, "No sessionFactory specified");

    // check if there is any transaction going on
    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
    if (sessionHolder != null && sessionHolder.getSession() != null)
        return sessionHolder.getSession();

    if (!allowCreate && !TransactionSynchronizationManager.isSynchronizationActive()) {
        throw new IllegalStateException("No session bound to thread, " + "and configuration does not allow creation of non-transactional one here");
    }

    LOG.debug("Opening JCR Session");
    Session session = sessionFactory.getSession();

    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        LOG.debug("Registering transaction synchronization for JCR session");
        // Use same session for further JCR actions within the transaction
        // thread object will get removed by synchronization at transaction
        // completion.
        sessionHolder = sessionFactory.getSessionHolder(session);
        sessionHolder.setSynchronizedWithTransaction(true);
        TransactionSynchronizationManager.registerSynchronization(new JcrSessionSynchronization(sessionHolder, sessionFactory));
        TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder);
    }

    return session;
}
 
Example 7
Source File: GrailsHibernateTemplate.java    From gorm-hibernate5 with Apache License 2.0 5 votes vote down vote up
/**
 * Prepare the given Criteria object, applying cache settings and/or a
 * transaction timeout.
 *
 * @param criteria the Criteria object to prepare
 * @deprecated Deprecated because Hibernate Criteria are deprecated
 */
@Deprecated
protected void prepareCriteria(Criteria criteria) {
    if (cacheQueries) {
        criteria.setCacheable(true);
    }
    if (shouldPassReadOnlyToHibernate()) {
        criteria.setReadOnly(true);
    }
    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
    if (sessionHolder != null && sessionHolder.hasTimeout()) {
        criteria.setTimeout(sessionHolder.getTimeToLiveInSeconds());
    }
}
 
Example 8
Source File: DataSourceUtils.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Actually close the given Connection, obtained from the given DataSource.
 * Same as {@link #releaseConnection}, but throwing the original SQLException.
 * <p>Directly accessed by {@link TransactionAwareDataSourceProxy}.
 * @param con the Connection to close if necessary
 * (if this is {@code null}, the call will be ignored)
 * @param dataSource the DataSource that the Connection was obtained from
 * (may be {@code null})
 * @throws SQLException if thrown by JDBC methods
 * @see #doGetConnection
 */
public static void doReleaseConnection(@Nullable Connection con, @Nullable DataSource dataSource) throws SQLException {
	if (con == null) {
		return;
	}
	if (dataSource != null) {
		ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource);
		if (conHolder != null && connectionEquals(conHolder, con)) {
			// It's the transactional Connection: Don't close it.
			conHolder.released();
			return;
		}
	}
	doCloseConnection(con, dataSource);
}
 
Example 9
Source File: HibernateTransactionManager.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected Object doGetTransaction() {
	HibernateTransactionObject txObject = new HibernateTransactionObject();
	txObject.setSavepointAllowed(isNestedTransactionAllowed());

	SessionHolder sessionHolder =
			(SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory());
	if (sessionHolder != null) {
		if (logger.isDebugEnabled()) {
			logger.debug("Found thread-bound Session [" +
					SessionFactoryUtils.toString(sessionHolder.getSession()) + "] for Hibernate transaction");
		}
		txObject.setSessionHolder(sessionHolder);
	}
	else if (this.hibernateManagedSession) {
		try {
			Session session = getSessionFactory().getCurrentSession();
			if (logger.isDebugEnabled()) {
				logger.debug("Found Hibernate-managed Session [" +
						SessionFactoryUtils.toString(session) + "] for Spring-managed transaction");
			}
			txObject.setExistingSession(session);
		}
		catch (HibernateException ex) {
			throw new DataAccessResourceFailureException(
					"Could not obtain Hibernate-managed Session for Spring-managed transaction", ex);
		}
	}

	if (getDataSource() != null) {
		ConnectionHolder conHolder = (ConnectionHolder)
				TransactionSynchronizationManager.getResource(getDataSource());
		txObject.setConnectionHolder(conHolder);
	}

	return txObject;
}
 
Example 10
Source File: HibernateTransactionManager.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected Object doGetTransaction() {
	HibernateTransactionObject txObject = new HibernateTransactionObject();
	txObject.setSavepointAllowed(isNestedTransactionAllowed());

	SessionHolder sessionHolder =
			(SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory());
	if (sessionHolder != null) {
		if (logger.isDebugEnabled()) {
			logger.debug("Found thread-bound Session [" + sessionHolder.getSession() + "] for Hibernate transaction");
		}
		txObject.setSessionHolder(sessionHolder);
	}
	else if (this.hibernateManagedSession) {
		try {
			Session session = this.sessionFactory.getCurrentSession();
			if (logger.isDebugEnabled()) {
				logger.debug("Found Hibernate-managed Session [" + session + "] for Spring-managed transaction");
			}
			txObject.setExistingSession(session);
		}
		catch (HibernateException ex) {
			throw new DataAccessResourceFailureException(
					"Could not obtain Hibernate-managed Session for Spring-managed transaction", ex);
		}
	}

	if (getDataSource() != null) {
		ConnectionHolder conHolder = (ConnectionHolder)
				TransactionSynchronizationManager.getResource(getDataSource());
		txObject.setConnectionHolder(conHolder);
	}

	return txObject;
}
 
Example 11
Source File: PersistenceManagerFactoryUtils.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Apply the current transaction timeout, if any, to the given JDO Query object.
 * @param query the JDO Query object
 * @param pmf JDO PersistenceManagerFactory that the Query was created for
 * @throws JDOException if thrown by JDO methods
 */
public static void applyTransactionTimeout(Query query, PersistenceManagerFactory pmf) throws JDOException {
	Assert.notNull(query, "No Query object specified");
	PersistenceManagerHolder pmHolder =
			(PersistenceManagerHolder) TransactionSynchronizationManager.getResource(pmf);
	if (pmHolder != null && pmHolder.hasTimeout() &&
			pmf.supportedOptions().contains("javax.jdo.option.DatastoreTimeout")) {
		int timeout = (int) pmHolder.getTimeToLiveInMillis();
		query.setDatastoreReadTimeoutMillis(timeout);
		query.setDatastoreWriteTimeoutMillis(timeout);
	}
}
 
Example 12
Source File: UserDaoTest.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 13
Source File: TXAspectProcessor.java    From tcc-transaction with Apache License 2.0 5 votes vote down vote up
private void assertTransactional()throws Throwable{
    DataSource dataSource= dataSourceAdaptor.getDataSource();
    Assert.notNull(dataSource,"datasource can not empty");
    ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource);
    if (conHolder == null || conHolder.getConnectionHandle()==null || !conHolder.isSynchronizedWithTransaction()) {
        throw new DistributedTransactionException("transaction connection is null");
    }
}
 
Example 14
Source File: HibernateInterceptor.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
	Session session = getSession();
	SessionHolder sessionHolder =
			(SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory());

	boolean existingTransaction = (sessionHolder != null && sessionHolder.containsSession(session));
	if (existingTransaction) {
		logger.debug("Found thread-bound Session for HibernateInterceptor");
	}
	else {
		if (sessionHolder != null) {
			sessionHolder.addSession(session);
		}
		else {
			TransactionSynchronizationManager.bindResource(getSessionFactory(), new SessionHolder(session));
		}
	}

	FlushMode previousFlushMode = null;
	try {
		previousFlushMode = applyFlushMode(session, existingTransaction);
		enableFilters(session);
		Object retVal = methodInvocation.proceed();
		flushIfNecessary(session, existingTransaction);
		return retVal;
	}
	catch (HibernateException ex) {
		if (this.exceptionConversionEnabled) {
			throw convertHibernateAccessException(ex);
		}
		else {
			throw ex;
		}
	}
	finally {
		if (existingTransaction) {
			logger.debug("Not closing pre-bound Hibernate Session after HibernateInterceptor");
			disableFilters(session);
			if (previousFlushMode != null) {
				session.setFlushMode(previousFlushMode);
			}
		}
		else {
			SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, getSessionFactory());
			if (sessionHolder == null || sessionHolder.doesNotHoldNonDefaultSession()) {
				TransactionSynchronizationManager.unbindResource(getSessionFactory());
			}
		}
	}
}
 
Example 15
Source File: DataSourceUtils.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * 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 16
Source File: ExtendedEntityManagerCreator.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
@Nullable
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
	// Invocation on EntityManager interface coming in...

	if (method.getName().equals("equals")) {
		// Only consider equal when proxies are identical.
		return (proxy == args[0]);
	}
	else if (method.getName().equals("hashCode")) {
		// Use hashCode of EntityManager proxy.
		return hashCode();
	}
	else if (method.getName().equals("getTargetEntityManager")) {
		// Handle EntityManagerProxy interface.
		return this.target;
	}
	else if (method.getName().equals("unwrap")) {
		// Handle JPA 2.0 unwrap method - could be a proxy match.
		Class<?> targetClass = (Class<?>) args[0];
		if (targetClass == null) {
			return this.target;
		}
		else if (targetClass.isInstance(proxy)) {
			return proxy;
		}
	}
	else if (method.getName().equals("isOpen")) {
		if (this.containerManaged) {
			return true;
		}
	}
	else if (method.getName().equals("close")) {
		if (this.containerManaged) {
			throw new IllegalStateException("Invalid usage: Cannot close a container-managed EntityManager");
		}
		ExtendedEntityManagerSynchronization synch = (ExtendedEntityManagerSynchronization)
				TransactionSynchronizationManager.getResource(this.target);
		if (synch != null) {
			// Local transaction joined - don't actually call close() before transaction completion
			synch.closeOnCompletion = true;
			return null;
		}
	}
	else if (method.getName().equals("getTransaction")) {
		if (this.synchronizedWithTransaction) {
			throw new IllegalStateException(
					"Cannot obtain local EntityTransaction from a transaction-synchronized EntityManager");
		}
	}
	else if (method.getName().equals("joinTransaction")) {
		doJoinTransaction(true);
		return null;
	}
	else if (method.getName().equals("isJoinedToTransaction")) {
		// Handle JPA 2.1 isJoinedToTransaction method for the non-JTA case.
		if (!this.jta) {
			return TransactionSynchronizationManager.hasResource(this.target);
		}
	}

	// Do automatic joining if required. Excludes toString, equals, hashCode calls.
	if (this.synchronizedWithTransaction && method.getDeclaringClass().isInterface()) {
		doJoinTransaction(false);
	}

	// Invoke method on current EntityManager.
	try {
		return method.invoke(this.target, args);
	}
	catch (InvocationTargetException ex) {
		throw ex.getTargetException();
	}
}
 
Example 17
Source File: GrailsHibernateTemplate.java    From gorm-hibernate5 with Apache License 2.0 4 votes vote down vote up
protected boolean isSessionTransactional(Session session) {
    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
    return sessionHolder != null && sessionHolder.getSession() == session;
}
 
Example 18
Source File: AbstractHibernateSession.java    From gorm-hibernate5 with Apache License 2.0 4 votes vote down vote up
@Override
public boolean hasTransaction() {
    Object resource = TransactionSynchronizationManager.getResource(hibernateTemplate.getSessionFactory());
    return resource != null;
}
 
Example 19
Source File: AbstractCompensatingTransactionManagerDelegate.java    From spring-ldap with Apache License 2.0 4 votes vote down vote up
public Object doGetTransaction() throws TransactionException {
	CompensatingTransactionHolderSupport holder = (CompensatingTransactionHolderSupport) TransactionSynchronizationManager
			.getResource(getTransactionSynchronizationKey());
       return new CompensatingTransactionObject(holder);
}
 
Example 20
Source File: DataSourceUtils.java    From effectivejava with Apache License 2.0 3 votes vote down vote up
/**
 * Determine whether the given JDBC Connection is transactional, that is,
 * bound to the current thread by Spring's transaction facilities.
 * @param con the Connection to check
 * @param dataSource the DataSource that the Connection was obtained from
 * (may be {@code null})
 * @return whether the Connection is transactional
 */
public static boolean isConnectionTransactional(Connection con, DataSource dataSource) {
	if (dataSource == null) {
		return false;
	}
	ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource);
	return (conHolder != null && connectionEquals(conHolder, con));
}