Hibernate's transaction management

Source: Internet
Author: User

Hibernate's transaction management

A transaction (Transaction) is the basic logical unit of work that can be used to ensure that the database is properly modified to prevent data from being partially modified and that the data is incomplete, or that it is interfered with by the user at the time of modification. As a software designer, you must understand the transaction and make reasonable use of it to ensure that the database holds the correct and complete data. The database provides the user with a way to save the current program state, called a transaction commit (commit), and a method called a transaction rollback (rollback) when the transaction executes, ignoring the current state and returning to the previously saved state.

1 Characteristics of the transaction

Transactions have atomicity (atomicity), consistency (consistency), isolation (isolation), and persistence (durability) 4 properties, called acid. These 4 properties are described below.

Atomicity: Bundles the operations performed in a transaction into an atomic unit, that is, the data modifications that are made to the firm, either all executed or not executed.

Consistency: When a transaction is complete, all data must be kept in a consistent state, and in the relevant data, all rules must be applied to the modification of the transaction to maintain the integrity of all the data. At the end of the transaction, all internal data structures should be correct.

Isolation: Modifications made by a concurrent transaction must be isolated from any changes made by any other firm. The state that the data is in when the transaction is viewing the data, either before it is modified by another concurrent transaction, or after it has been modified by another concurrent transaction, that is, the transaction does not view the data being modified by another concurrent transaction. This isolation method is also called Serializable.

Persistence: After a transaction completes, its effect on the system is permanent, even if a system failure occurs.

2 Transaction Isolation

Transaction isolation means that for a running transaction, it is as if there is only one transaction in the system, and no other concurrent transactions exist. In most cases, a fully isolated transaction is seldom used. But a transaction that is not completely isolated brings up some of the following problems.  Update lost (Lost update): Two transactions are attempting to update a row of data, causing the transaction to throw an unexpected exit, two transactions update is wasted. Dirty data (Dirty Read): Dirty reads occur if the second application uses the data that was modified by the first application, and this data is in an uncommitted state.  The first application might then request that the modified data be rolled back, causing the data used by the second transaction to be corrupted, the so-called "dirty". Non-rereading (unrepeatable Read): One transaction reads the same row two times, but the data read two times is not the same, it is called non-stressed.  If a transaction can modify and delete the data before committing the data, it will be non-stressed. Phantom Read (Phantom Read): A transaction executed two queries and found that the second query result was a row more than the first query, possibly because another transaction inserted a new row between the two queries.  For the above problems caused by incomplete isolation of transactions, some isolation levels are proposed to protect against these problems. READ UNCOMMITTED: Indicates that a transaction's changes are visible to other transactions before it is committed. Such dirty reading, non-repetition, and phantom reading are permissible. When a transaction has been written to a row of data but not committed, no other transaction can write to this row of data, but any transaction may read any data.  This isolation level is implemented using a write lock. Read Committed: READ UNCOMMITTED data is not allowed, it is implemented using temporary read lock and write lock.  This isolation level does not allow dirty reads, but is not reread and Phantom reads are allowed.? Reread (Repeatable Read): Indicates that the transaction guarantees that the same data can be read again without failure.  This isolation level does not allow dirty reads and non-stress, but Phantom reads appear. Serializable (Serializable): Provides the strictest transaction isolation. This isolation level does not allow transactions to be executed in parallel, only serial execution is allowed. In this way, dirty reading, non-stress, or phantom reading can occur. The relationship between transaction isolation and isolation levels is shown in table 9-2. Table 9-2 relationship between transaction isolation and isolation levels

Isolation level Dirty Reads (Dirty read) Non-rereading (unrepeatable read) Phantom Read (Phantom Read)
Read operation not committed (uncommitted) possible possible possible
Read operation submitted (Committed) No way possible possible
Can be reread (repeatable Read) No way No way possible
Serializable (Serializable) No way No way No way

In a practical application, developers often fail to determine what isolation level to use. Too severe a level will degrade the performance of concurrent transactions, but insufficient isolation levels will result in minor bugs that only occur if the system is heavily loaded (that is, concurrency is critical). In general, read UNCOMMITTED is a risky operation. A rollback or failure of one transaction can affect another parallel transaction, or the data in memory that is inconsistent with the database. This data may be read by another transaction and committed to the database. This is not allowed at all. In addition, most programs do not require serializable isolation (Serializable isolation). Although it does not allow Phantom reading, in general, Phantom Reading is not a big problem. Serializable isolation requires significant system overhead, and few people use this transactional isolation pattern in real-world development. The optional isolation level that is left now is that the read operation has been committed (read Committed) and can be reread (repeatable read). Hibernate is a good way to support the repeatable Read isolation level. 3 Setting the isolation level in the Hibernate configuration file

The JDBC Connection database uses the default isolation level, which reads the read Committed and is reread (repeatable read). In Hibernate configuration file hibernate.properties, you can modify the isolation level:

#hibernate. Connection.isolation 4

In the previous line of code, the isolation level for hibernate transactions is 4, what does that mean? The number of levels is as follows.

1: READ UNCOMMITTED 2: Read action submitted (read Committed) 4: Reread (Repeatable Read) 8: Serializable (Serializable)

Therefore, the number 4 represents the "reread" isolation level. If you want to make the above statement valid, you should remove the comment "#" before this statement line:

Hibernate.connection.isolation 4
You can also include the following code in the configuration file Hibernate.cfg.xml:
<session-factory>.....//set the isolation level to 4<property name= "Hibernate.connection.isolation" >4</PROPERTY> </session-factory>
Hibernate obtains the value of the isolation level from the configuration file before starting a transaction. 4 using JDBC transactions in Hibernate

Hibernate provides a lightweight encapsulation of JDBC, which itself does not have transactional capabilities at design time. Hibernate encapsulates the underlying jdbctransaction or jtatransaction, and then sets the outer shell of the transaction and session, in fact, by delegating the underlying JDBC or JTA to handle the transaction function.

To use a transaction in Hibernate, you can specify the use of Jdbctransaction or jtatransaction in its configuration file. In Hibernate.properties, look for the "transaction.factory_class" keyword to get the following configuration:

# Hibernate.transaction.factory_class org.hibernate.transaction.jtatransactionfactory# Hibernate.transaction.factory_class org.hibernate.transaction.JDBCTransactionFactory

Hibernate's transaction factory class can be set to Jdbctransactionfactory or Jtatransactionfactory. If not configured, Hibernate will assume that the transaction used by the system is a JDBC transaction.

In the JDBC commit mode, if the database connection is autocommit (auto commit mode), the transaction is committed after each SQL statement execution, and if there is a task after the commit, a new transaction begins.

Hibernate in session control, after obtaining the database connection, immediately cancel the auto-commit mode, that is, hibernate in a BeginTransaction () method to execute the session, The JDBC layer's Setautocommit (false) is automatically called. If you want to provide your own database connection and use your own SQL statements, in order to implement a transaction, you must first turn off Autocommit (Setautocommit (false)) and commit the transaction at the end of the transaction.

Using JDBC transactions is the simplest way to implement transaction management, and Hibernate's encapsulation of JDBC transactions is simple. Here is an example of using JDBC transactions in Hibernate:

try {Session session = Hibernateutil.currentsession ();  Transaction tx = Session.begintransaction (); By default, a JDBC thing for (int i=0; i<10; i++) {Student stu = new Student (), Stu.setname ("Student" + i), Session.save (Stu) is turned on; }tx.commit (); Commit Transaction Session.close ();}   catch (Exception e) {... tx.rollback (); Transaction rollback}
5 using JTA transactions in Hibernate

JTA (Java Transaction API) is the EE solution for transactional services. Essentially, it is part of the EE model that describes the transactional interface that the developer uses directly or through the Java EE container to ensure that the business logic runs reliably.

The JTA has 3 interfaces, each of which is the UserTransaction interface, the TransactionManager interface, and the transaction interface. These interfaces share common things operations, such as commit () and rollback (), but also contain special transactional operations such as suspend (), resume (), and Enlist (), which appear only on specific interfaces to allow some degree of access control in the implementation.

In a system with multiple databases, a program may invoke data from several databases, require a distributed transaction, or be prepared to use JTA to manage long transactions across sessions, then a JTA transaction is required. Here's how to configure the JTA transaction in Hibernate's configuration file. Set the following in the Hibernate.properties file (uncomment "#" of the configuration line where the Jtatransactionfactory is located):

Hibernate.transaction.factory_class org.hibernate.transaction.jtatransactionfactory# Hibernate.transaction.factory_class org.hibernate.transaction.JDBCTransactionFactory
Or, configure the following in the Hibernate.cfg.xml file:
<session-factory>.....<property name= "Hibernate.transaction.factory_class" > Org.hibernate.transaction.jtatransactionfactory</property>......</session-factory>
Here is an example of applying a JTA transaction:
Javax.transaction.UserTransaction tx = NULL;TX = new InitialContext (). Lookup ("Javax.transaction.UserTransaction"); Tx.begin ();  Session S1 = sf.opensession ();....... s1.flush (); S1.close ();  Session s2 = sf.opensession ();....... s2.flush (); S2.close (); Tx.commit ();

Hibernate's transaction management

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.