Hibernate pessimistic lock and optimistic lock instance details, hibernate instance details

Source: Internet
Author: User

Hibernate pessimistic lock and optimistic lock instance details, hibernate instance details

This article mainly focuses on Hibernate pessimistic locks and optimistic locks. The details are as follows.

Pessimistic lock

Pessimistic locks are usually implemented by the database mechanism. during the entire process, data is locked (during query) as long as the transaction is not released (submitted/rolled back ), no user can view or modify it.

The following is a case study.

Case:Assume that the inventory of goods is 1000. When clerk 1 extracts the data and prepares to modify the data, but has something to do temporarily, he will leave. During this period, the number of retrieved data is reduced by 200, and then the number of retrieved data is reduced by 200, the reviewer 1 did not make any modification on the basis of 800. This is the so-called update loss, which can be solved by the pessimistic lock.

Inventory. java:

Public class Inventory {/* Inventory number */private String itemNo;/* Inventory name */private String itemName;/* Inventory quantity */private int quantity; // The setter and getter methods are omitted}

Inventory. hbm. xml:

<? Xml version = "1.0"?> <! DOCTYPE hibernate-mapping PUBLIC "-// Hibernate/Hibernate DTD ing DTD 3.0 // EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 

Test class:

Reviewer 1 loads data in a pessimistic lock mode and modifies the data!

Public void testLoad1 () {Session session = null; try {session = HibernateUtils. getSession (); session. beginTransaction ();/* adds a pessimistic lock during loading to prevent other users from accessing the */Inventory inv = (Inventory) session. load (Inventory. class, "1001", LockMode. UPGRADE);/* Get Data */System. out. println ("opt1 --> itemNo =" + inv. getItemNo (); System. out. println ("opt1 --> itemName =" + inv. getItemName (); System. out. println ("opt1 --> quantity =" + inv. getQuantity ();/* number minus 200 */inv. setQuantity (inv. getQuantity ()-200); session. getTransaction (). commit ();} catch (Exception e) {e. printStackTrace (); session. getTransaction (). rollback ();} finally {HibernateUtils. closeSession (session );}}

The operations of reviewer 2 and reviewer 1 are the same. They modify the data in the database!

Public void testLoad2 () {Session session = null; try {session = HibernateUtils. getSession (); session. beginTransaction ();/* adds a lock when loading data to prevent others from obtaining data */Inventory inv = (Inventory) session. load (Inventory. class, "1001", LockMode. UPGRADE);/* Get real data */System. out. println ("opt2 --> itemNo =" + inv. getItemNo (); System. out. println ("opt2 --> itemName =" + inv. getItemName (); System. out. println ("opt2 --> quantity =" + inv. getQuantity ();/* inventory minus 200 */inv. setQuantity (inv. getQuantity ()-200); session. getTransaction (). commit ();} catch (Exception e) {e. printStackTrace (); session. getTransaction (). rollback ();} finally {HibernateUtils. closeSession (session );}}

Note: The operations performed by the two auditors are the same. If the pessimistic lock is applied, the reviewer extracts the data and modifies the data. Before the reviewer 1 does not submit the transaction, reviewer 2 cannot access data and can only be in the waiting state. After the processor 1 submits the transaction, the reviewer 2 has the opportunity to operate the data in the database.

Through the above pessimistic Lock Case, we can find that the biggest benefit of the pessimistic lock is to prevent update loss. When the reviewer 1 is processing data, the reviewer 2 can only be in the waiting state, only after reviewer 1 submits a transaction can the reviewer 2 have the opportunity to modify the data. However, there is also a big problem, that is, if the reviewer 1 queries the data and the future generations will be gone, other people will have to wait for a long time, which is a waste of time, to solve this problem, we can use optimistic locks.

Optimistic lock

Optimistic locks are not true locks. In most cases, they are implemented using the data version method. Generally, a version field is added to the database, when reading data, you can read the version. When saving the data, you can determine whether the version value is smaller than the database version value. If it is smaller than the version value, it will not be updated; otherwise, it will be updated.

Set javaBean under optimistic locks,Inventory. java:

Public class Inventory {/* Inventory number */private String itemNo;/* Inventory name */private String itemName;/* Inventory quantity */private int quantity; /* Data version */private int version; // The setter and getter methods are omitted}

Inventory. hbm. xml:

<? Xml version = "1.0"?> <! DOCTYPE hibernate-mapping PUBLIC "-// Hibernate/Hibernate DTD ing DTD 3.0 // EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 

Note: The ing file using optimistic locks stipulates that the ing of the version field must be the first ing after the primary key ID.

Test:

Reviewer 1 processes data with optimistic locks:

Public void testLoad1 () {Session session = null; try {session = HibernateUtils. getSession (); session. beginTransaction ();/* load data under optimistic locks */Inventory inv = (Inventory) session. load (Inventory. class, "1001");/* actually retrieve data */System. out. println ("opt1 --> itemNo =" + inv. getItemNo (); System. out. println ("opt1 --> itemName =" + inv. getItemName (); System. out. println ("opt1 --> version =" + inv. getVersion (); System. out. println ("opt1 --> quantity =" + inv. getQuantity ();/* number minus 200 */inv. setQuantity (inv. getQuantity ()-200); session. getTransaction (). commit ();} catch (Exception e) {e. printStackTrace (); session. getTransaction (). rollback ();} finally {HibernateUtils. closeSession (session );}}

Reviewer 2 processes data with an optimistic lock (reviewer 2 can process data without submitting data)

Public void testLoad2 () {Session session = null; try {session = HibernateUtils. getSession (); session. beginTransaction ();/* load data under optimistic locks */Inventory inv = (Inventory) session. load (Inventory. class, "1001");/* actually retrieve data */System. out. println ("opt2 --> itemNo =" + inv. getItemNo (); System. out. println ("opt2 --> itemName =" + inv. getItemName (); System. out. println ("opt2 --> version =" + inv. getVersion (); System. out. println ("opt2 --> quantity =" + inv. getQuantity ();/* number minus 200 */inv. setQuantity (inv. getQuantity ()-200); session. getTransaction (). commit ();} catch (Exception e) {e. printStackTrace (); session. getTransaction (). rollback ();} finally {HibernateUtils. closeSession (session );}}

Note: When the number of data retrieved by the reviewer minus 200, the reviewer 2 can also operate the data, which is different from the pessimistic lock. When the reviewer 2 operates the data and submits the data, the version of the data in the database adds 1. When the reviewer 1 returns for transaction submission, an error message is displayed, indicating that the data has been updated. please reload the data.

Summary

Pessimistic locks affect high concurrency, so it is better to use optimistic locks.

The above is all the details about Hibernate pessimistic locks and optimistic locks, and I hope to help you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!

Related Article

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.