Class HibernateTransactionManager
- java.lang.Object
-
- io.micronaut.transaction.support.AbstractSynchronousStateTransactionManager<T>
-
- io.micronaut.transaction.support.AbstractSynchronousTransactionManager<java.sql.Connection>
-
- io.micronaut.transaction.hibernate5.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>SynchronousTransactionManagerimplementation for a single HibernateSessionFactory. 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 withMicronautSessionContext.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
-
-
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 voiddisconnectOnCompletion(org.hibernate.Session session)Disconnect a pre-existing Hibernate Session on transaction completion, returning its database connection but preserving its entity state.protected voiddoBegin(java.lang.Object transaction, io.micronaut.transaction.TransactionDefinition definition)protected voiddoCleanupAfterCompletion(java.lang.Object transaction)protected voiddoCommit(io.micronaut.transaction.support.DefaultTransactionStatus status)protected java.lang.ObjectdoGetTransaction()protected voiddoResume(java.lang.Object transaction, java.lang.Object suspendedResources)protected voiddoRollback(io.micronaut.transaction.support.DefaultTransactionStatus status)protected voiddoSetRollbackOnly(io.micronaut.transaction.support.DefaultTransactionStatus status)protected java.lang.ObjectdoSuspend(java.lang.Object transaction)java.sql.ConnectiongetConnection()protected java.sql.ConnectiongetConnection(java.lang.Object transaction)javax.sql.DataSourcegetDataSource()org.hibernate.InterceptorgetEntityInterceptor()javax.persistence.EntityManagerFactorygetResourceFactory()org.hibernate.SessionFactorygetSessionFactory()protected java.lang.ObjectgetTransactionStateKey()booleanhasConnection()protected booleanisExistingTransaction(java.lang.Object transaction)protected booleanisPhysicallyConnected(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 booleanisSameConnectionForEntireSession(org.hibernate.Session session)Return whether the given Hibernate Session will always hold the same JDBC Connection.voidsetAllowResultAccessAfterCompletion(boolean allowResultAccessAfterCompletion)Set whether to allow result access after completion, typically via Hibernate's ScrollableResults mechanism.voidsetHibernateManagedSession(boolean hibernateManagedSession)Set whether to operate on a Hibernate-managed Session, that is, whether to obtain the Session through Hibernate'sSessionFactory.getCurrentSession()instead ofSessionFactory.openSession()(with aTransactionSynchronizationManagercheck preceding it).voidsetPrepareConnection(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
-
-
-
-
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 fordataSource- The data source associated with the session factoryentityInterceptor- 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 fordataSource- The data source associated with the session factoryentityInterceptor- The configured entity interceptorname- The data source name
-
-
Method Detail
-
getTransactionStateKey
protected java.lang.Object getTransactionStateKey()
- Overrides:
getTransactionStateKeyin classio.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'sSessionFactory.getCurrentSession()instead ofSessionFactory.openSession()(with aTransactionSynchronizationManagercheck 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 thegetCurrentSession()call fails.This mode will typically be used in combination with a custom Hibernate
CurrentSessionContextimplementation 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 defaultMicronautSessionContext), in which case it subtly differs from the Spring-managed Session mode: The pre-bound Session will not receive aclear()call (on rollback) or adisconnect()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
nullif none. Resolves an entity interceptor bean name via the bean factory, if necessary.
-
getResourceFactory
public javax.persistence.EntityManagerFactory getResourceFactory()
- Specified by:
getResourceFactoryin interfaceio.micronaut.transaction.support.ResourceTransactionManager<javax.persistence.EntityManagerFactory,java.sql.Connection>
-
getConnection
protected java.sql.Connection getConnection(java.lang.Object transaction)
- Specified by:
getConnectionin classio.micronaut.transaction.support.AbstractSynchronousTransactionManager<java.sql.Connection>
-
doGetTransaction
protected java.lang.Object doGetTransaction()
- Specified by:
doGetTransactionin classio.micronaut.transaction.support.AbstractSynchronousTransactionManager<java.sql.Connection>
-
isExistingTransaction
protected boolean isExistingTransaction(java.lang.Object transaction)
- Overrides:
isExistingTransactionin classio.micronaut.transaction.support.AbstractSynchronousTransactionManager<java.sql.Connection>
-
doBegin
protected void doBegin(java.lang.Object transaction, io.micronaut.transaction.TransactionDefinition definition)- Specified by:
doBeginin classio.micronaut.transaction.support.AbstractSynchronousStateTransactionManager<java.sql.Connection>
-
doSuspend
protected java.lang.Object doSuspend(java.lang.Object transaction)
- Overrides:
doSuspendin classio.micronaut.transaction.support.AbstractSynchronousStateTransactionManager<java.sql.Connection>
-
doResume
protected void doResume(@Nullable java.lang.Object transaction, java.lang.Object suspendedResources)- Overrides:
doResumein classio.micronaut.transaction.support.AbstractSynchronousStateTransactionManager<java.sql.Connection>
-
doCommit
protected void doCommit(io.micronaut.transaction.support.DefaultTransactionStatus status)
- Specified by:
doCommitin classio.micronaut.transaction.support.AbstractSynchronousStateTransactionManager<java.sql.Connection>
-
doRollback
protected void doRollback(io.micronaut.transaction.support.DefaultTransactionStatus status)
- Specified by:
doRollbackin classio.micronaut.transaction.support.AbstractSynchronousStateTransactionManager<java.sql.Connection>
-
doSetRollbackOnly
protected void doSetRollbackOnly(io.micronaut.transaction.support.DefaultTransactionStatus status)
- Overrides:
doSetRollbackOnlyin classio.micronaut.transaction.support.AbstractSynchronousStateTransactionManager<java.sql.Connection>
-
doCleanupAfterCompletion
protected void doCleanupAfterCompletion(java.lang.Object transaction)
- Overrides:
doCleanupAfterCompletionin classio.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:
getConnectionin interfaceio.micronaut.transaction.TransactionOperations<java.sql.Connection>
-
hasConnection
public boolean hasConnection()
- Specified by:
hasConnectionin interfaceio.micronaut.transaction.TransactionOperations<java.sql.Connection>
-
-