Hibernate is a lightweight package of JDBC that does not itself have transaction management capabilities, and at the transaction management level, Hibernate entrusts it to the underlying JDBC or JTA for transaction management and scheduling.
Hibernate's default transaction handling mechanism is based on jdbctransaction, or it can be configured with JTA as a transaction management implementation through configuration file settings:
<session-factory>
......
<property name = "Hibernate.transaction.factory_class" >
Net.sf.hibernate.transaction.JTATransactionFactory
</session-factory>
1. JDBC-based transaction management
Hibernate encapsulation of JDBC transactions is straightforward. For example:
Session=sessionfactory.opensession ();
Transaction tx= session.begintransaction ();
......
Tx.commit ();
It is important to note that in Sessionfactory.opensession (), Hibernate initializes the database connection and, at the same time, sets its autocommit to off state, which means that When the session is obtained from Sessionfactory, its Autocommit property is closed, and the following code does not have any effect on the transactional database.
Session=sessionfactory.opensession ();
Session.save (user);
Session.close ();
If you want to make the code really work on the database, you must display the call Transaction directive
Session=sessionfactory.opensession ();
Transaction tx = Session.begintransaction ();
Session.save (user);
Tx.commit ();
Session.close ();
2. Transaction management based on JTA
JTA provides the ability to manage transactions across sessions, which is the biggest difference from jdbctransaction.
The JDBC transaction is managed by connection, that is, the transaction management is actually implemented in the JDBC connection, and the transaction cycle is limited to the life cycle of connection, for JDBC-based Transaction's hibernate transaction management mechanism, transaction management is implemented in the JDBC connection supported by the session, and the transaction cycle is limited to the life cycle of the session.
JTA transaction management is implemented by the JTA container, JTA container to the current join transaction of many connection scheduling, to achieve its transactional requirements, JTA transaction cycle can span multiple JDBC connection life cycle, similarly, for JTA-based transactions of Hibernate, JTA transactions span multiple sessions. It is important to note that connection involved in JTA transactions need to avoid interfering with transaction management, and if JTA Transaction is used, Hibernate's Transaction function should not be invoked.
JTA and Hibernate transactions