Class HibernateTransactionManager

java.lang.Object
org.springframework.transaction.support.AbstractPlatformTransactionManager
org.springframework.orm.hibernate5.HibernateTransactionManager
All Implemented Interfaces:
Serializable, Aware, BeanFactoryAware, InitializingBean, ConfigurableTransactionManager, PlatformTransactionManager, ResourceTransactionManager, TransactionManager

public class HibernateTransactionManager extends AbstractPlatformTransactionManager implements ResourceTransactionManager, BeanFactoryAware, InitializingBean
PlatformTransactionManager implementation for a single Hibernate SessionFactory. Binds a Hibernate Session from the specified factory to the thread, potentially allowing for one thread-bound Session per factory. SessionFactory.getCurrentSession() is required for Hibernate access code that needs to support this transaction handling mechanism, with the SessionFactory being configured with SpringSessionContext.

Supports custom isolation levels, and timeouts that get applied as Hibernate transaction timeouts.

This transaction manager is appropriate for applications that use a single Hibernate SessionFactory for transactional data access, but it also supports direct DataSource access within a transaction (i.e. plain JDBC code working with the same DataSource). This allows for mixing services which access Hibernate and services which use plain JDBC (without being aware of Hibernate)! Application code needs to stick to the same simple Connection lookup pattern as with DataSourceTransactionManager (i.e. DataSourceUtils.getConnection(javax.sql.DataSource) or going through a TransactionAwareDataSourceProxy).

Note: To be able to register a DataSource's Connection for plain JDBC code, this instance needs to be aware of the DataSource (setDataSource(javax.sql.DataSource)). The given DataSource should obviously match the one used by the given SessionFactory.

JTA (usually through JtaTransactionManager) is necessary for accessing multiple transactional resources within the same transaction. The DataSource that Hibernate uses needs to be JTA-enabled in such a scenario (see container setup).

This transaction manager supports nested transactions via JDBC 3.0 Savepoints. The AbstractPlatformTransactionManager.setNestedTransactionAllowed(boolean) "nestedTransactionAllowed"} flag defaults to "false", though, as nested transactions will just apply to the JDBC Connection, not to the Hibernate Session and its cached entity objects and related context. You can manually set the flag to "true" if you want to use nested transactions for JDBC access code which participates in Hibernate transactions (provided that your JDBC driver supports Savepoints). Note that Hibernate itself does not support nested transactions! Hence, do not expect Hibernate access code to semantically participate in a nested transaction.

NOTE: Hibernate ORM 6.x is officially only supported as a JPA provider. Please use LocalContainerEntityManagerFactoryBean with JpaTransactionManager there instead.

Since:
4.2
Author:
Juergen Hoeller
See Also:
  • Constructor Details

    • HibernateTransactionManager

      public HibernateTransactionManager()
      Create a new HibernateTransactionManager instance. A SessionFactory has to be set to be able to use it.
      See Also:
    • HibernateTransactionManager

      public HibernateTransactionManager(SessionFactory sessionFactory)
      Create a new HibernateTransactionManager instance.
      Parameters:
      sessionFactory - the SessionFactory to manage transactions for
  • Method Details

    • setSessionFactory

      public void setSessionFactory(@Nullable SessionFactory sessionFactory)
      Set the SessionFactory that this instance should manage transactions for.
    • getSessionFactory

      @Nullable public SessionFactory getSessionFactory()
      Return the SessionFactory that this instance should manage transactions for.
    • obtainSessionFactory

      protected final SessionFactory obtainSessionFactory()
      Obtain the SessionFactory for actual use.
      Returns:
      the SessionFactory (never null)
      Throws:
      IllegalStateException - in case of no SessionFactory set
      Since:
      5.0
    • setDataSource

      public void setDataSource(@Nullable DataSource dataSource)
      Set the JDBC DataSource that this instance should manage transactions for. The DataSource should match the one used by the Hibernate SessionFactory: for example, you could specify the same JNDI DataSource for both.

      If the SessionFactory was configured with LocalDataSourceConnectionProvider, i.e. by Spring's LocalSessionFactoryBean with a specified "dataSource", the DataSource will be auto-detected: You can still explicitly specify the DataSource, but you don't need to in this case.

      A transactional JDBC Connection for this DataSource will be provided to application code accessing this DataSource directly via DataSourceUtils or JdbcTemplate. The Connection will be taken from the Hibernate Session.

      The DataSource specified here should be the target DataSource to manage transactions for, not a TransactionAwareDataSourceProxy. Only data access code may work with TransactionAwareDataSourceProxy, while the transaction manager needs to work on the underlying target DataSource. If there's nevertheless a TransactionAwareDataSourceProxy passed in, it will be unwrapped to extract its target DataSource.

      NOTE: For scenarios with many transactions that just read data from Hibernate's cache (and do not actually access the database), consider using a LazyConnectionDataSourceProxy for the actual target DataSource. Alternatively, consider switching "prepareConnection" to false. In both cases, this transaction manager will not eagerly acquire a JDBC Connection for each Hibernate Session anymore (as of Spring 5.1).

      See Also:
    • getDataSource

      @Nullable public DataSource getDataSource()
      Return the JDBC DataSource that this instance manages transactions for.
    • setAutodetectDataSource

      public void setAutodetectDataSource(boolean autodetectDataSource)
      Set whether to autodetect a JDBC DataSource used by the Hibernate SessionFactory, if set via LocalSessionFactoryBean's setDataSource. Default is "true".

      Can be turned off to deliberately ignore an available DataSource, in order to not expose Hibernate transactions as JDBC transactions for that DataSource.

      See Also:
    • setPrepareConnection

      public void setPrepareConnection(boolean prepareConnection)
      Set whether to prepare the underlying JDBC Connection of a transactional Hibernate Session, that is, whether to apply a transaction-specific isolation level and/or the transaction's read-only flag to the underlying JDBC Connection.

      Default is "true". If you turn this flag off, the transaction manager will not support per-transaction isolation levels anymore. It will not call Connection.setReadOnly(true) for read-only transactions anymore either. If this flag is turned off, no cleanup of a JDBC Connection is required after a transaction, since no Connection settings will get modified.

      See Also:
    • setAllowResultAccessAfterCompletion

      @Deprecated(since="5.3.29") public void setAllowResultAccessAfterCompletion(boolean allowResultAccessAfterCompletion)
      Deprecated.
      as of 5.3.29 since Hibernate 5.x aggressively closes ResultSets on commit, making it impossible to rely on ResultSet holdability. Also, Spring does not provide an equivalent setting on JpaTransactionManager.
      Set whether to allow result access after completion, typically via Hibernate's ScrollableResults mechanism.

      Default is "false". Turning this flag on enforces over-commit holdability on the underlying JDBC Connection (if "prepareConnection" is on) and skips the disconnect-on-completion step.

      See Also:
    • setHibernateManagedSession

      public void setHibernateManagedSession(boolean hibernateManagedSession)
      Set whether to operate on a Hibernate-managed Session instead of a Spring-managed Session, that is, whether to obtain the Session through Hibernate's SessionFactory.getCurrentSession() instead of SessionFactory.openSession() (with a Spring TransactionSynchronizationManager check preceding it).

      Default is "false", i.e. using a Spring-managed Session: taking the current thread-bound Session if available (e.g. in an Open-Session-in-View scenario), creating a new Session for the current transaction otherwise.

      Switch this flag to "true" in order to enforce use of a Hibernate-managed Session. Note that this requires SessionFactory.getCurrentSession() to always return a proper Session when called for a Spring-managed transaction; transaction begin will fail if the getCurrentSession() call fails.

      This mode will typically be used in combination with a custom Hibernate CurrentSessionContext implementation that stores Sessions in a place other than Spring's TransactionSynchronizationManager. It may also be used in combination with Spring's Open-Session-in-View support (using Spring's default SpringSessionContext), in which case it subtly differs from the Spring-managed Session mode: The pre-bound Session will not receive a clear() call (on rollback) or a disconnect() call (on transaction completion) in such a scenario; this is rather left up to a custom CurrentSessionContext implementation (if desired).

    • setSessionInitializer

      public void setSessionInitializer(Consumer<Session> sessionInitializer)
      Specify a callback for customizing every Hibernate Session resource created for a new transaction managed by this HibernateTransactionManager.

      This enables convenient customizations for application purposes, e.g. setting Hibernate filters.

      Since:
      5.3
      See Also:
    • setEntityInterceptorBeanName

      public void setEntityInterceptorBeanName(String entityInterceptorBeanName)
      Set the bean name of a Hibernate entity interceptor that allows to inspect and change property values before writing to and reading from the database. Will get applied to any new Session created by this transaction manager.

      Requires the bean factory to be known, to be able to resolve the bean name to an interceptor instance on session creation. Typically used for prototype interceptors, i.e. a new interceptor instance per session.

      Can also be used for shared interceptor instances, but it is recommended to set the interceptor reference directly in such a scenario.

      Parameters:
      entityInterceptorBeanName - the name of the entity interceptor in the bean factory
      See Also:
    • setEntityInterceptor

      public void setEntityInterceptor(@Nullable Interceptor entityInterceptor)
      Set a Hibernate entity interceptor that allows to inspect and change property values before writing to and reading from the database. Will get applied to any new Session created by this transaction manager.

      Such an interceptor can either be set at the SessionFactory level, i.e. on LocalSessionFactoryBean, or at the Session level, i.e. on HibernateTransactionManager.

      See Also:
    • getEntityInterceptor

      @Nullable public Interceptor getEntityInterceptor() throws IllegalStateException, BeansException
      Return the current Hibernate entity interceptor, or null if none. Resolves an entity interceptor bean name via the bean factory, if necessary.
      Throws:
      IllegalStateException - if bean name specified but no bean factory set
      BeansException - if bean name resolution via the bean factory failed
      See Also:
    • setBeanFactory

      public void setBeanFactory(BeanFactory beanFactory)
      The bean factory just needs to be known for resolving entity interceptor bean names. It does not need to be set for any other mode of operation.
      Specified by:
      setBeanFactory in interface BeanFactoryAware
      Parameters:
      beanFactory - owning BeanFactory (never null). The bean can immediately call methods on the factory.
      See Also:
    • afterPropertiesSet

      public void afterPropertiesSet()
      Description copied from interface: InitializingBean
      Invoked by the containing BeanFactory after it has set all bean properties and satisfied BeanFactoryAware, ApplicationContextAware etc.

      This method allows the bean instance to perform validation of its overall configuration and final initialization when all bean properties have been set.

      Specified by:
      afterPropertiesSet in interface InitializingBean
    • getResourceFactory

      public Object getResourceFactory()
      Description copied from interface: ResourceTransactionManager
      Return the resource factory that this transaction manager operates on, e.g. a JDBC DataSource or a JMS ConnectionFactory.

      This target resource factory is usually used as resource key for TransactionSynchronizationManager's resource bindings per thread.

      Specified by:
      getResourceFactory in interface ResourceTransactionManager
      Returns:
      the target resource factory (never null)
      See Also:
    • doGetTransaction

      protected Object doGetTransaction()
      Description copied from class: AbstractPlatformTransactionManager
      Return a transaction object for the current transaction state.

      The returned object will usually be specific to the concrete transaction manager implementation, carrying corresponding transaction state in a modifiable fashion. This object will be passed into the other template methods (e.g. doBegin and doCommit), either directly or as part of a DefaultTransactionStatus instance.

      The returned object should contain information about any existing transaction, that is, a transaction that has already started before the current getTransaction call on the transaction manager. Consequently, a doGetTransaction implementation will usually look for an existing transaction and store corresponding state in the returned transaction object.

      Specified by:
      doGetTransaction in class AbstractPlatformTransactionManager
      Returns:
      the current transaction object
      See Also:
    • isExistingTransaction

      protected boolean isExistingTransaction(Object transaction)
      Description copied from class: AbstractPlatformTransactionManager
      Check if the given transaction object indicates an existing transaction (that is, a transaction which has already started).

      The result will be evaluated according to the specified propagation behavior for the new transaction. An existing transaction might get suspended (in case of PROPAGATION_REQUIRES_NEW), or the new transaction might participate in the existing one (in case of PROPAGATION_REQUIRED).

      The default implementation returns false, assuming that participating in existing transactions is generally not supported. Subclasses are of course encouraged to provide such support.

      Overrides:
      isExistingTransaction in class AbstractPlatformTransactionManager
      Parameters:
      transaction - the transaction object returned by doGetTransaction
      Returns:
      if there is an existing transaction
      See Also:
    • doBegin

      protected void doBegin(Object transaction, TransactionDefinition definition)
      Description copied from class: AbstractPlatformTransactionManager
      Begin a new transaction with semantics according to the given transaction definition. Does not have to care about applying the propagation behavior, as this has already been handled by this abstract manager.

      This method gets called when the transaction manager has decided to actually start a new transaction. Either there wasn't any transaction before, or the previous transaction has been suspended.

      A special scenario is a nested transaction without savepoint: If useSavepointForNestedTransaction() returns "false", this method will be called to start a nested transaction when necessary. In such a context, there will be an active transaction: The implementation of this method has to detect this and start an appropriate nested transaction.

      Specified by:
      doBegin in class AbstractPlatformTransactionManager
      Parameters:
      transaction - the transaction object returned by doGetTransaction
      definition - a TransactionDefinition instance, describing propagation behavior, isolation level, read-only flag, timeout, and transaction name
    • doSuspend

      protected Object doSuspend(Object transaction)
      Description copied from class: AbstractPlatformTransactionManager
      Suspend the resources of the current transaction. Transaction synchronization will already have been suspended.

      The default implementation throws a TransactionSuspensionNotSupportedException, assuming that transaction suspension is generally not supported.

      Overrides:
      doSuspend in class AbstractPlatformTransactionManager
      Parameters:
      transaction - the transaction object returned by doGetTransaction
      Returns:
      an object that holds suspended resources (will be kept unexamined for passing it into doResume)
      See Also:
    • doResume

      protected void doResume(@Nullable Object transaction, Object suspendedResources)
      Description copied from class: AbstractPlatformTransactionManager
      Resume the resources of the current transaction. Transaction synchronization will be resumed afterwards.

      The default implementation throws a TransactionSuspensionNotSupportedException, assuming that transaction suspension is generally not supported.

      Overrides:
      doResume in class AbstractPlatformTransactionManager
      Parameters:
      transaction - the transaction object returned by doGetTransaction
      suspendedResources - the object that holds suspended resources, as returned by doSuspend
      See Also:
    • doCommit

      protected void doCommit(DefaultTransactionStatus status)
      Description copied from class: AbstractPlatformTransactionManager
      Perform an actual commit of the given transaction.

      An implementation does not need to check the "new transaction" flag or the rollback-only flag; this will already have been handled before. Usually, a straight commit will be performed on the transaction object contained in the passed-in status.

      Specified by:
      doCommit in class AbstractPlatformTransactionManager
      Parameters:
      status - the status representation of the transaction
      See Also:
    • doRollback

      protected void doRollback(DefaultTransactionStatus status)
      Description copied from class: AbstractPlatformTransactionManager
      Perform an actual rollback of the given transaction.

      An implementation does not need to check the "new transaction" flag; this will already have been handled before. Usually, a straight rollback will be performed on the transaction object contained in the passed-in status.

      Specified by:
      doRollback in class AbstractPlatformTransactionManager
      Parameters:
      status - the status representation of the transaction
      See Also:
    • doSetRollbackOnly

      protected void doSetRollbackOnly(DefaultTransactionStatus status)
      Description copied from class: AbstractPlatformTransactionManager
      Set the given transaction rollback-only. Only called on rollback if the current transaction participates in an existing one.

      The default implementation throws an IllegalTransactionStateException, assuming that participating in existing transactions is generally not supported. Subclasses are of course encouraged to provide such support.

      Overrides:
      doSetRollbackOnly in class AbstractPlatformTransactionManager
      Parameters:
      status - the status representation of the transaction
    • doCleanupAfterCompletion

      protected void doCleanupAfterCompletion(Object transaction)
      Description copied from class: AbstractPlatformTransactionManager
      Cleanup resources after transaction completion.

      Called after doCommit and doRollback execution, on any outcome. The default implementation does nothing.

      Should not throw any exceptions but just issue warnings on errors.

      Overrides:
      doCleanupAfterCompletion in class AbstractPlatformTransactionManager
      Parameters:
      transaction - the transaction object returned by doGetTransaction
    • disconnectOnCompletion

      protected void disconnectOnCompletion(Session session)
      Disconnect a pre-existing Hibernate Session on transaction completion, returning its database connection but preserving its entity state.

      The default implementation calls the equivalent of Session.disconnect(). Subclasses may override this with a no-op or with fine-tuned disconnection logic.

      Parameters:
      session - the Hibernate Session to disconnect
      See Also:
    • convertHibernateAccessException

      protected DataAccessException convertHibernateAccessException(HibernateException ex)
      Convert the given HibernateException to an appropriate exception from the org.springframework.dao hierarchy.

      Will automatically apply a specified SQLExceptionTranslator to a Hibernate JDBCException, else rely on Hibernate's default translation.

      Parameters:
      ex - the HibernateException that occurred
      Returns:
      a corresponding DataAccessException
      See Also: