Hibernate Reading Notes ----- optimistic lock and pessimistic lock

Source: Internet
Author: User

When using Hibernate, we may encounter multiple users simultaneously modifying the same data, which may cause dirty data and data inconsistency. To avoid data loss during update, Hibernate uses a lock mechanism.
 
Hibernate provides two lock mechanisms: Pessimistic lock and optimistic lock.
Pessimistic lock: when data is loaded, it is locked until the lock is released. Other users can modify the lock.
Optimistic lock: when modifying the data, compare the data by version number or timestamp, and check whether the data is consistent to implement locking.
 
I. pessimistic lock
Pessimistic locks rely on the locking mechanism provided by the database. Hibernate implements the pessimistic lock mechanism by using the for update clause of the database.
 
Hibernate has the following five locking mechanisms:
1. LockMode. NONE: No lock mechanism
2. LockMode. WRITE: Hibernate automatically obtains the Insert and Update records.
3. LockMode. READ: Hibernate automatically obtains the data when reading the record.
4. LockMode. UPGRADE: use the database's for update clause to lock
5. LockMode. UPGRADE_NOWAIT: specific implementation of Oracle. Use the Oracle for update nowait clause to implement locking.
 
Pessimistic locking is generally implemented through the following three methods:
1. Criteria. setLockMode
2. Query. setLockMode
3. Session. lock
The following example locks a query:
[Java]
Public void query (int id ){
Session session = HibernateUtil. getSession ();
Transaction tx = session. beginTransaction ();
String hql = "from Users as u where id =: id ";
List list = session. createQuery (hql)
. SetLockMode ("u", LockMode. UPGRADE) // execute lock
. SetInteger ("id", id)
. List ();
For (Iterator iterator = list. iterator (); iterator. hasNext ();){
Users users = (Users) iterator. next ();
System. out. println (users. getBirthday ());
}
}

The generated SQL statement is as follows:
[SQL]
Select users0 _. id as id0 _, users0 _. ver as ver0 _,
 
Users0 _. birthday as birthday0 _, users0 _. first_name as first4_0 _, users0 _. last_name as last5_0 _ from Users users0 _
 
With (updlock, rowlock) where users0 _. id =?
After the pessimistic lock locks the data, it will "Occupy" The data until it is released. Other users can update the data. There is a problem here. If it is always occupied, other users will never be able to update the data, which is not conducive to concurrency. Optimistic locks can be used for solutions to this problem.
 
Ii. Optimistic lock
Optimistic locks are mostly implemented based on the data version record mechanism. What is the data version? Add a version ID for the data. In the database table-based version solution, you can add a "version" field to the database table. When reading the data, read the version number together, and then add one to the version number when updating the data. In this case, the version data of the submitted data is compared with the current version information recorded in the database table. If the submitted data version number is greater than the current version number of the database table, it is updated, otherwise, expired data is considered.
 
We can specify an optimistic lock by combining the optimistic-lock attribute of the class descriptor with the version descriptor.
1. none: No optimistic lock
2. version: Optimistic Locking through the version Mechanism
3. dirty: checks the changed attributes to implement optimistic locks.
4. all: Optimistic Locking by checking all attributes
In the persistence class that implements optimistic locks, we need to add a version attribute for the persistence class and provide the corresponding getter and setter methods. As follows:
[Java]
Public class Users {
Private int id;
Private Date birthday;
Private Name name;
Private int version;
 
// Remove the getter and setter Methods
}

Configuration file:
[Html]
<Hibernate-mapping package = "com. hibernate. domain">
<Class name = "Users" optimistic-lock = "version">
<Id name = "id">
<Generator class = "native"/>
</Id>
<Version name = "version"/>

<Property name = "birthday"/>

<! -- Map component elements -->
<Component name = "name">
<! -- The name attribute of the ing component points to the object that contains -->
<Property name = "firstName" column = "first_name"/>
<Property name = "lastName" column = "last_name"/>
</Component>
</Class>
</Hibernate-mapping>

Note: The version node must appear after the ID node.
 
Here we declare a version attribute to store the version information of a user. Each update operation on the user table will change the version attribute: Add 1. If we try to start another Session before tx. commit and perform operations on the same user name, it is the case of concurrent updates:
[Java]
Public void update (){
// Enable transaction tx1
Session session1 = HibernateUtil. getSession ();
Transaction tx1 = session1.beginTransaction ();
Users users1 = (Users) session1.get (Users. class, 1); // get the user with id 1

// Enable transaction tx2
Session session2 = HibernateUtil. getSession ();
Transaction tx2 = session2.beginTransaction ();
Users users2 = (Users) session2.get (Users. class, 1); // gets the user whose id is 1

Users1.getName (). setFirstName ("first name1 ");
Users2.getName (). setFirstName ("first name2 ");

Tx1.commit (); // ......
Tx2.commit (); // .......... 2
 
Session1.close ();
Session2.clear ();

}

Run the above Code. The Code will throw StaleObjectStateException in... 2, and indicates that the version check fails.

 
Here, the submitter succeeded, and the submitter failed. The current transaction is attempting to commit an expired data. By capturing this exception, we can handle it when optimistic lock validation fails.
Author: chenssy

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.