Hibernate Getting Started 27 - Transaction Management

xiaoxiao2021-03-06  44

Getting Started 27 - Transaction Management

The transaction is a set of atomic operations (a set of SQL execution) work units, all atomic operations in this working unit are isolated from other transactions, exempt from cross-phase updates of the data source, and all atoms in the transaction. Operation, all do you have successful, all failure (even if there is only one failure, all atomic operations must be revoked). In JDBC, you can use Connection to manage your transaction. You can set the connection of the connection to false. After you get a series of SQL statements, you call the CONNECTION COMMIT () to send a change. If an error occurs in the middle, you will undo all the execution ,E.g:

Try {

.....

Connection.SetAutocommit (False);

.....

// A series of SQL operations

CONNECTION.COMMIT ();

} catCH (Exception) {

// Error, undo all changes

Connection.rollback ();

}

Hibernate itself does not have a transaction management function. It relies on JDBC or JTA transaction management capabilities. The preset is to use JDBC transaction management. In fact, the following procedure is just a simple package for JDBC transaction management:

Try {

SESSION = sessionFactory.openSession ();

Transaction tx = session.begintransaction ();

....

TX.comMit ();

} catch (exception e) {

TX.rollback ();

}

When executing OpenSession (), hibernate is actually executing BeginTransAction (), which actually executes the setAutocommit (FALSE) method, the last tx.commit () is the COMMIT () method of calling connections. If you are interested, you can study the Begin () and commit () method in net.sf.hibernate.transaction.jdbcTransAction, you can find the corresponding JDBC code.

SESSION = sessionFactory.openSession (); <- connection connection = ....;

Tx = session.begintransactioin (); <- connection.setautocommit (false);

TX.comMit (); <- connect.commit ();

Session.Close (); <- connection.close ();

So use JDBC transaction management, and finally perform transaction's commit (). If not, all instructions under the session will not have effects before the SESSION. Hibernate can use JTA-based transaction management through profiles, JTA transaction management can span several sessions, not like JDBC transaction management only in a session, we write as follows in hibernate.cfg.xml:

....

Session S1 = sessionFactory.openSession ();

.... // Some Save, Update, etc.

S1.Flush ();

S1.Close ();

...

Session S2 = sf.openSession ();

...

s2.flush ();

S2.Close ();

....

TX.comMit ();

Similarly, if you are interested, you can see Begin () and commit () method code in net.sf.hibernate.transaction.jtatransaction, see how Hibernate is encapsulated by JTA's transaction management code.

转载请注明原文地址:https://www.9cbs.com/read-63516.html

New Post(0)