Optimistic and pessimistic locks in hibernate

Source: Internet
Author: User

Hibernate supports two types of locks: pessimistic lock (pessimistic Locking) and optimistic lock (optimistic Locking)

Pessimistic lock: Refers to the database data by the external modification of the conservative attitude (whether it is the transaction of the system, or the transaction of external systems), the entire process of data processing is in a locked state. The pessimistic lock in hibernate is dependent on the lock mechanism in the database (because only the database layer can control the data operation of the system and the external system to the database).

For example, "SELECT * from user where username= ' Johnson ' for update" This SQL locks all username= ' Johnson ' records in the user table and cannot be modified by the outside world until this transaction is committed.

The pessimistic lock in Hibernate is also implemented based on the lock mechanism of the database.

String="from TUser as user where user.name=‘Lili‘"= session.createQuery(hqlStr);query.setLockMode("user",LockMode.//加锁List= query.list();//执行查询,获取数据

The first parameter in the above code specifies that the returned record of the Setlockmode alias is locked.
The resulting SQL is:

select tuser0_. ID  as  id , Tuser0_.name  as  name , tuser0_. Group_idas  group_id, Tuser0_.user_type as  user _type, Tuser0_.sex as  sexfrom  t_user tuser0_ Span class= "Hljs-keyword" >where  (Tuser0_. Name  = ' Erica ') for  update  

It is visible that hibernate implements the pessimistic locking mechanism through the FOR UPDATE clause in the database.
Hibernate plus Lock mode:
Lockmode.none: no lock mechanism.
LockMode.WRITE:Hibernate is automatically acquired when the Insert and Update records are recorded.
The LockMode.READ:Hibernate is automatically retrieved when the record is read.
These three types of locking mechanisms are typically used internally by hibernate, such as hibernate to automatically add WRITE locks to the target object in the Save method implementation, in order to ensure that the object is not modified by the outside world during the update process.
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.
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

In contrast to pessimistic locks, the locking mechanism of optimistic locking is relatively loose. Pessimistic lock most of the situation relies on the database lock mechanism to ensure the maximum degree of exclusivity. On the other hand, the cost of the database is very large, especially for long transactions.

Optimistic locks are mostly implemented based on the data version (versions) recording mechanism. That is, add a version ID in the data table, read out the data, along with this version of the identity read together, when updating the data, the version identifier plus 1. The submission version data is compared to the current version information in the database, and if the version number in the submitted data is greater than the current version number of the data table, the update is allowed, otherwise it is considered to be out of date data.

There are two main ways of optimistic locking in Hibernate: Version and timestamp

Example of a configuration:

    <?xml version= "1.0"?>      <! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "Http://hibernate. Sourceforge.net/hibernate-mapping-3.0.dtd ">      <hibernate-mapping>          <class name="test. Dir " table=" T_dir ">              <ID name="id" type="string" Unsaved-value ="null">               <column name="Id_" sql-type="char " not-null=  "True" />               <generator class="Uuid.hex" />          </ID>          <!--Here the version node must be equipped with the ID --            <version column="Version_" name="Version" />               < property name= "name" column="name_" type=" String "/>              < property name="Size" column="Size_" type= "Long" />              <many-to-one name="dir" column="Pid_" class=" Test. Dir " />          </class>      </hibernate-mapping>  

The negative problem with optimistic locking: If two different transactions read one data at a time and update, the program will report an exception: Org.hibernate.StaleObjectStateException:Row was updated or deleted by Another transaction (or Unsaved-value mapping was incorrect). This is the time to catch the exception and then process and remind the user to submit again.
Similarly, optimistic locking has limitations. is only the control of the system's transaction concurrency, and the external system operation of the data table can not be controlled, at this time there is a solution is: in the storage process to achieve optimistic locking mechanism, so whether it is the system or external system transaction operations, the database can be controlled. Therefore, in the design phase, as far as possible to consider all kinds of situations, whether in the terminal to achieve good, or database-side implementation of the better.

Optimistic and pessimistic locks in hibernate

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.