Hibernate optimistic lock and pessimistic lock use

Source: Internet
Author: User

Hibernate supports two types of locking mechanisms:
The "Pessimistic lock (pessimistic Locking)" and "optimistic Lock (optimisticlocking)" are usually called.

Pessimistic lock implementation, often rely on the database provided by the lock mechanism (also only the database layer provides a lock mechanism to truly guarantee the exclusivity of data access, otherwise, even in this system to implement the locking mechanism, there is no guarantee that the external system will not modify the data).

Hibernate's lock modes are:
? Lockmode.none: no lock mechanism.
? LockMode.WRITE:Hibernate automatically when insert and update records
Get.
? The LockMode.READ:Hibernate is automatically retrieved when the record is read.
These three locking mechanisms are typically used internally by hibernate, such as hibernate to ensure that the update
The object is not modified by the outside world, and a write lock is automatically added to the target object in the Save method implementation.
? Lockmode.upgrade: Use the database's for UPDATE clause to lock.
? Lockmode. A specific implementation of the Upgrade_nowait:oracle, using Oracle's for UPDATE NOWAIT clause to implement the lock.

Hibernate's pessimistic lock is also a database-based lock mechanism implementation. The following code implements the locking of the query record:

1 String hqlstr =   " From TUser as user where user.name= ' Erica ' " ;
2 Query Query = session.createquery (HQLSTR);
3 Query.setlockmode ( " User " , Lockmode.upgrade); // Locking
4 List userlist = query.list (); // execute the query,

Gets the data Query.setlockmode locks the record for a particular alias in the query statement (we specify an alias "user" for the Tuser Class), which is to lock all the returned user records. Observe the SQL statements generated by hibernate during the run time:

1 select Tuser0_.id as ID, tuser0_.name as name, tuser0_.group_id as group_id, Tuser0_.user_type as User_type , tuser0_.sex as sex from T_user tuser0_ where (tuser0_.name = ' Erica ') for update< /c5>

Here hibernate implements the pessimistic locking mechanism by using the database's for UPDATE clause.

The above two kinds of locking mechanism is more commonly used in the application layer, lock is generally implemented by the following methods:
Criteria.setlockmode
Query.setlockmode
Session.lock
Note that locking is really done through the lock mechanism of the database only if the lock is set before the query starts (that is, before the hiberate generates SQL), otherwise the data has been loaded through a select SQL that does not contain a FOR UPDATE clause. The so-called database lock also can not talk about.






Optimistic locking, mostly based on the data version (versions) recording mechanism implementation. What is a data version? is to add a version identity to the data, which is typically done by adding a "version" field to the database table in the version solution based on the database table. When the data is read, the version number is read together, and then the version number is added one after the update. At this point, the version data of the submitted data is compared to the current version information of the database table corresponding to the record, and if the submitted version number is greater than the current version number of the database table, it is updated, otherwise it is considered to be outdated data.

1. First, add the Optimistic-lock property to the class descriptor for Tuser:

< Hibernate - Mapping >
< class
Name = " Org.hibernate.sample.TUser "
Table = " T_user "
Dynamic - Update = " true "
Dynamic - Insert = " true "
Optimistic - Lock = " version "
>
......
</ class >
</ Hibernate - Mapping >  

Add a Version Property descriptor
Code content

1 < Hibernate - Mapping >
2 < class
3 name = " Org.hibernate.sample.TUser "
4 Table = " T_user "
5 Dynamic - Update = " true "
6 Dynamic - Insert = " true "
7 optimistic - Lock = " version "
8 >
9 < ID
Ten name = " ID "
One column = " ID "
A type = " Java.lang.Integer "
- >
- < Generator class = " native " >
the </ Generator >
- </ ID >
- < version
- column = " version "
+ name = " version "
- type = " Java.lang.Integer "
+ />
A ...
at </ class >
- </ Hibernate - Mapping >
-



Note The version node must appear after the ID node.
Here we declare a version property, which holds the user's release information, and is saved in the Tuser table's versions field. At this point, if we try to write a piece of code, update the record data in the Tuser table, such as:
Code content

1 Criteria Criteria = Session.createcriteria (TUser. class );
2 Criteria.add (Expression.eq ( " name " , " Erica " ));
3 List userlist = criteria.list ();
4 TUser User = (TUser) userlist.get ( 0 );
5 Transaction TX = Session.begintransaction ();
6 User.setusertype ( 1 ); // Update usertype field
7 Tx.commit ();
8


Each time we update the Tuser, we can see that the version in the database is incremented. And if we try to start another session before Tx.commit, manipulate the user named Erica to emulate the Concurrency update scenario:
Code content

1 Session Session = getsession ();
2 Criteria Criteria = Session.createcriteria (TUser. class );
3 Criteria.add (Expression.eq ( " name " , " Erica " ));
4 Session Session2 = getsession ();
5 Criteria criteria2 = Session2.createcriteria (TUser. class );
6 Criteria2.add (Expression.eq ( " name " , " Erica " ));
7 List userlist = criteria.list ();
8 List UserList2 = criteria2.list (); TUser User = (TUser) userlist.get ( 0 );
9 TUser User2 = (TUser) userlist2.get ( 0 );
Ten Transaction TX = session.begintransaction ();
One Transaction tx2 = session2.begintransaction ();
A User2.setusertype ( About );
- Tx2.commit ();
- User.setusertype ( 1 );
the Tx.commit ();
-

Executing the above code, the code throws an staleobjectstateexception exception at Tx.commit () and indicates that the version check failed and that the current transaction is attempting to submit an expired data. By catching this exception, we can handle the optimistic lock check when it fails.




A comparison between pessimistic and optimistic locks:
Pessimistic locking relies on the lock mechanism of the database in most cases, to ensure the maximum degree of exclusivity of the operation. But then comes the large amount of database performance overhead, especially for long transactions, the overhead is often unbearable;
Relative pessimistic lock, the optimistic locking mechanism adopts a more relaxed locking mechanism. Optimistic locking mechanism is often based on the data storage logic in the system, so there are some limitations, as in the above example, because the optimistic locking mechanism is implemented in our system, the update from the external system is not controlled by our system, it may cause dirty data to be updated into the database. In
During the system design phase, we should take full account of the possibility of these situations and make adjustments (such as implementing the optimistic locking policy in the database stored procedure, open only the data update path based on this stored procedure, rather than exposing the database table directly to the external).
Hibernate has built-in optimistic locking implementations in its data access engine. If you do not take into account the external system to update the database, using hibernate to provide a transparent optimistic lock implementation, will greatly enhance our productivity.
Hibernate can be specified by using the Optimistic-lock property of the class descriptor in conjunction with the version descriptor.
The Optimistic-lock property resembles the following selectable value:
? None
No optimistic lock
? Version
Optimistic locking via version mechanism
? Dirty
Optimistic locking by checking for properties that have changed
? All
Optimistic locking by checking all properties
The optimistic locking mechanism which is implemented by version is the optimistic lock implemented by hibernate, and it is also the only locking mechanism that is still effective when the data object is changed from the session. Therefore, in general, we all choose the version mode as the hibernate optimistic lock implementation mechanism.


Hibernate optimistic lock and pessimistic lock use

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.