How to use Hibernate directly
This article mainly shows you "how to use Hibernate directly", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to use Hibernate directly" this article.
When using Hibernate directly, at the end of the transaction, write a sentence: tx.commit (), the source code of this commit () is:
Public void commit () throws HibernateException {if (! begun) {throw new TransactionException ("Transaction not successfully started");} log.debug ("commit"); if (! transactionContext.isFlushModeNever () & & callback) {transactionContext.managedFlush (); / / if an exception occurs during / / flush, user must call / / rollback ()} notifyLocalSynchsBeforeTransactionCompletion (); if (callback) {jdbcContext.beforeTransactionCompletion (this);} try {commitAndResetAutoCommit () / / key code, which commits the transaction and restores the autocommit attribute of connection to true log.debug ("committed JDBC Connection"); committed = true; if (callback) {jdbcContext.afterTransactionCompletion (true, this);} notifyLocalSynchsAfterTransactionCompletion (Status.STATUS_COMMITTED);} catch (SQLException e) {log.error ("JDBC commit failed", e); commitFailed = true; if (callback) {jdbcContext.afterTransactionCompletion (false, this);} notifyLocalSynchsAfterTransactionCompletion (Status.STATUS_UNKNOWN) Throw new TransactionException ("JDBC commit failed", e);} finally {closeIfRequired ();}}
In the above code, the source code for the commitAndResetAutoCommit () method is as follows:
Private void commitAndResetAutoCommit () throws SQLException {try {jdbcContext.connection () .commit (); / / needless to say, this paragraph can understand} finally {toggleAutoCommit (); / / the function of this paragraph is to restore the autocommit attribute of connection to true}}
The toggleAutoCommit () source code of the above code is as follows:
Private void toggleAutoCommit () {try {if (toggleAutoCommit) {log.debug ("re-enabling autocommit"); jdbcContext.connection () .setAutoCommit (true); / / the meaning of this line of code is very clear}} catch (Exception sqle) {log.error ("Could not toggle autocommit", sqle);}}
Therefore, if you are using Hibernate directly, managing its session manually, and manually opening and closing transactions, you can guarantee your transactions (which seems to be complete nonsense).
The above is all the contents of the article "how to use Hibernate directly". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!