Class HibernateTransactionManager

  • All Implemented Interfaces:
    io.micronaut.transaction.support.ResourceTransactionManager<javax.persistence.EntityManagerFactory,​java.sql.Connection>, io.micronaut.transaction.support.TransactionStateOperations<java.sql.Connection,​io.micronaut.transaction.support.SynchronousTransactionState>, io.micronaut.transaction.SynchronousTransactionManager<java.sql.Connection>, io.micronaut.transaction.TransactionManager, io.micronaut.transaction.TransactionOperations<java.sql.Connection>, java.io.Serializable

    @EachBean(javax.sql.DataSource.class)
    @Replaces(io.micronaut.transaction.jdbc.DataSourceTransactionManager.class)
    public class HibernateTransactionManager
    extends io.micronaut.transaction.support.AbstractSynchronousTransactionManager<java.sql.Connection>
    implements io.micronaut.transaction.support.ResourceTransactionManager<javax.persistence.EntityManagerFactory,​java.sql.Connection>
    SynchronousTransactionManager 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 MicronautSessionContext.

    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).

    This transaction manager supports nested transactions via JDBC 3.0 Savepoints. The AbstractSynchronousStateTransactionManager.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.

    Since:
    4.2
    See Also:
    SessionFactory.getCurrentSession(), DataSourceUtils.getConnection(javax.sql.DataSource), DataSourceUtils.releaseConnection(java.sql.Connection, javax.sql.DataSource), DataSourceTransactionManager, Serialized Form
    • Field Summary

      • Fields inherited from class io.micronaut.transaction.support.AbstractSynchronousStateTransactionManager

        logger
    • Constructor Summary

      Constructors 
      Constructor Description
      HibernateTransactionManager​(org.hibernate.SessionFactory sessionFactory, javax.sql.DataSource dataSource, org.hibernate.Interceptor entityInterceptor)
      Create a new HibernateTransactionManager instance.
      HibernateTransactionManager​(org.hibernate.SessionFactory sessionFactory, javax.sql.DataSource dataSource, org.hibernate.Interceptor entityInterceptor, java.lang.String name)
      Create a new HibernateTransactionManager instance.
    • Method Summary

      All Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      protected void disconnectOnCompletion​(org.hibernate.Session session)
      Disconnect a pre-existing Hibernate Session on transaction completion, returning its database connection but preserving its entity state.
      protected void doBegin​(java.lang.Object transaction, io.micronaut.transaction.TransactionDefinition definition)  
      protected void doCleanupAfterCompletion​(java.lang.Object transaction)  
      protected void doCommit​(io.micronaut.transaction.support.DefaultTransactionStatus status)  
      protected java.lang.Object doGetTransaction()  
      protected void doResume​(java.lang.Object transaction, java.lang.Object suspendedResources)  
      protected void doRollback​(io.micronaut.transaction.support.DefaultTransactionStatus status)  
      protected void doSetRollbackOnly​(io.micronaut.transaction.support.DefaultTransactionStatus status)  
      protected java.lang.Object doSuspend​(java.lang.Object transaction)  
      java.sql.Connection getConnection()  
      protected java.sql.Connection getConnection​(java.lang.Object transaction)  
      javax.sql.DataSource getDataSource()  
      org.hibernate.Interceptor getEntityInterceptor()  
      javax.persistence.EntityManagerFactory getResourceFactory()  
      org.hibernate.SessionFactory getSessionFactory()  
      protected java.lang.Object getTransactionStateKey()  
      boolean hasConnection()  
      protected boolean isExistingTransaction​(java.lang.Object transaction)  
      protected boolean isPhysicallyConnected​(org.hibernate.Session session)
      Determine whether the given Session is (still) physically connected to the database, that is, holds an active JDBC Connection internally.
      protected boolean isSameConnectionForEntireSession​(org.hibernate.Session session)
      Return whether the given Hibernate Session will always hold the same JDBC Connection.
      void setAllowResultAccessAfterCompletion​(boolean allowResultAccessAfterCompletion)
      Set whether to allow result access after completion, typically via Hibernate's ScrollableResults mechanism.
      void setHibernateManagedSession​(boolean hibernateManagedSession)
      Set whether to operate on a Hibernate-managed Session, that is, whether to obtain the Session through Hibernate's SessionFactory.getCurrentSession() instead of SessionFactory.openSession() (with a TransactionSynchronizationManager check preceding it).
      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.
      • Methods inherited from class io.micronaut.transaction.support.AbstractSynchronousTransactionManager

        commit, doCleanupAfterCompletion, doDestroyState, doGetTransaction, execute, executeRead, executeWrite, find, findOrCreateState, getConnection, getState, getTransaction, invokeAfterCompletion, isExistingTransaction, newTransactionStatus, newTransactionStatus, prepareSynchronization, prepareSynchronization, prepareTransactionStatus, registerAfterCompletionWithExistingTransaction, registerAfterCompletionWithExistingTransaction, resume, rollback, suspend, triggerBeforeCommit, triggerBeforeCompletion
      • Methods inherited from class io.micronaut.transaction.support.AbstractSynchronousStateTransactionManager

        commit, determineTimeout, execute, executeRead, executeWrite, getDefaultTimeout, getTransaction, getTransactionSynchronization, invokeAfterCompletion, isFailEarlyOnGlobalRollbackOnly, isGlobalRollbackOnParticipationFailure, isNestedTransactionAllowed, isRollbackOnCommitFailure, isValidateExistingTransaction, prepareForCommit, prepareTransactionStatus, resume, rollback, setDefaultTimeout, setFailEarlyOnGlobalRollbackOnly, setGlobalRollbackOnParticipationFailure, setNestedTransactionAllowed, setRollbackOnCommitFailure, setTransactionSynchronization, setValidateExistingTransaction, shouldCommitOnGlobalRollbackOnly, suspend, triggerBeforeCommit, triggerBeforeCompletion, useSavepointForNestedTransaction
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
      • Methods inherited from interface io.micronaut.transaction.SynchronousTransactionManager

        commit, getTransaction, rollback
      • Methods inherited from interface io.micronaut.transaction.TransactionOperations

        execute, executeRead, executeWrite
    • Constructor Detail

      • HibernateTransactionManager

        public HibernateTransactionManager​(@Parameter
                                           org.hibernate.SessionFactory sessionFactory,
                                           javax.sql.DataSource dataSource,
                                           @Nullable
                                           org.hibernate.Interceptor entityInterceptor)
        Create a new HibernateTransactionManager instance.
        Parameters:
        sessionFactory - the SessionFactory to manage transactions for
        dataSource - The data source associated with the session factory
        entityInterceptor - The configured entity interceptor
      • HibernateTransactionManager

        @Inject
        public HibernateTransactionManager​(@Parameter
                                           org.hibernate.SessionFactory sessionFactory,
                                           javax.sql.DataSource dataSource,
                                           @Nullable
                                           org.hibernate.Interceptor entityInterceptor,
                                           @Parameter
                                           java.lang.String name)
        Create a new HibernateTransactionManager instance.
        Parameters:
        sessionFactory - the SessionFactory to manage transactions for
        dataSource - The data source associated with the session factory
        entityInterceptor - The configured entity interceptor
        name - The data source name
    • Method Detail

      • getTransactionStateKey

        protected java.lang.Object getTransactionStateKey()
        Overrides:
        getTransactionStateKey in class io.micronaut.transaction.support.AbstractSynchronousTransactionManager<java.sql.Connection>
      • getSessionFactory

        @NonNull
        public org.hibernate.SessionFactory getSessionFactory()
        Returns:
        Return the SessionFactory that this instance should manage transactions for.
      • getDataSource

        @Nullable
        public javax.sql.DataSource getDataSource()
        Returns:
        Return the JDBC DataSource that this instance manages transactions for.
      • 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.

        Parameters:
        prepareConnection - Whether to prepare the connection
        See Also:
        Connection.setTransactionIsolation(int), Connection.setReadOnly(boolean)
      • setAllowResultAccessAfterCompletion

        public void setAllowResultAccessAfterCompletion​(boolean allowResultAccessAfterCompletion)
        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.

        Parameters:
        allowResultAccessAfterCompletion - Whether to allow result access after completion
        See Also:
        Connection.setHoldability(int), ResultSet.HOLD_CURSORS_OVER_COMMIT, disconnectOnCompletion(Session)
      • setHibernateManagedSession

        public void setHibernateManagedSession​(boolean hibernateManagedSession)
        Set whether to operate on a Hibernate-managed Session, that is, whether to obtain the Session through Hibernate's SessionFactory.getCurrentSession() instead of SessionFactory.openSession() (with a 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 MicronautSessionContext), 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).

        Parameters:
        hibernateManagedSession - True if hibernate managed sessions should be used
      • getEntityInterceptor

        @Nullable
        public org.hibernate.Interceptor getEntityInterceptor()
        Returns:
        Return the current Hibernate entity interceptor, or null if none. Resolves an entity interceptor bean name via the bean factory, if necessary.
      • getResourceFactory

        public javax.persistence.EntityManagerFactory getResourceFactory()
        Specified by:
        getResourceFactory in interface io.micronaut.transaction.support.ResourceTransactionManager<javax.persistence.EntityManagerFactory,​java.sql.Connection>
      • getConnection

        protected java.sql.Connection getConnection​(java.lang.Object transaction)
        Specified by:
        getConnection in class io.micronaut.transaction.support.AbstractSynchronousTransactionManager<java.sql.Connection>
      • doGetTransaction

        protected java.lang.Object doGetTransaction()
        Specified by:
        doGetTransaction in class io.micronaut.transaction.support.AbstractSynchronousTransactionManager<java.sql.Connection>
      • isExistingTransaction

        protected boolean isExistingTransaction​(java.lang.Object transaction)
        Overrides:
        isExistingTransaction in class io.micronaut.transaction.support.AbstractSynchronousTransactionManager<java.sql.Connection>
      • doBegin

        protected void doBegin​(java.lang.Object transaction,
                               io.micronaut.transaction.TransactionDefinition definition)
        Specified by:
        doBegin in class io.micronaut.transaction.support.AbstractSynchronousStateTransactionManager<java.sql.Connection>
      • doSuspend

        protected java.lang.Object doSuspend​(java.lang.Object transaction)
        Overrides:
        doSuspend in class io.micronaut.transaction.support.AbstractSynchronousStateTransactionManager<java.sql.Connection>
      • doResume

        protected void doResume​(@Nullable
                                java.lang.Object transaction,
                                java.lang.Object suspendedResources)
        Overrides:
        doResume in class io.micronaut.transaction.support.AbstractSynchronousStateTransactionManager<java.sql.Connection>
      • doCommit

        protected void doCommit​(io.micronaut.transaction.support.DefaultTransactionStatus status)
        Specified by:
        doCommit in class io.micronaut.transaction.support.AbstractSynchronousStateTransactionManager<java.sql.Connection>
      • doRollback

        protected void doRollback​(io.micronaut.transaction.support.DefaultTransactionStatus status)
        Specified by:
        doRollback in class io.micronaut.transaction.support.AbstractSynchronousStateTransactionManager<java.sql.Connection>
      • doSetRollbackOnly

        protected void doSetRollbackOnly​(io.micronaut.transaction.support.DefaultTransactionStatus status)
        Overrides:
        doSetRollbackOnly in class io.micronaut.transaction.support.AbstractSynchronousStateTransactionManager<java.sql.Connection>
      • doCleanupAfterCompletion

        protected void doCleanupAfterCompletion​(java.lang.Object transaction)
        Overrides:
        doCleanupAfterCompletion in class io.micronaut.transaction.support.AbstractSynchronousTransactionManager<java.sql.Connection>
      • disconnectOnCompletion

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

        The default implementation simply calls 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:
        Session.disconnect()
      • isSameConnectionForEntireSession

        protected boolean isSameConnectionForEntireSession​(org.hibernate.Session session)
        Return whether the given Hibernate Session will always hold the same JDBC Connection. This is used to check whether the transaction manager can safely prepare and clean up the JDBC Connection used for a transaction.

        The default implementation checks the Session's connection release mode to be "on_close".

        Parameters:
        session - the Hibernate Session to check
        Returns:
        Whether the same connection is needed for the whole session
        See Also:
        ConnectionReleaseMode.ON_CLOSE
      • isPhysicallyConnected

        protected boolean isPhysicallyConnected​(org.hibernate.Session session)
        Determine whether the given Session is (still) physically connected to the database, that is, holds an active JDBC Connection internally.
        Parameters:
        session - the Hibernate Session to check
        Returns:
        Is the session physically connected
        See Also:
        isSameConnectionForEntireSession(Session)
      • getConnection

        @NonNull
        public java.sql.Connection getConnection()
        Specified by:
        getConnection in interface io.micronaut.transaction.TransactionOperations<java.sql.Connection>
      • hasConnection

        public boolean hasConnection()
        Specified by:
        hasConnection in interface io.micronaut.transaction.TransactionOperations<java.sql.Connection>