Hibernate lock mechanism-pessimistic lock and optimistic lock

Source: Internet
Author: User

Hibernate lock mechanism. Let's make a summary today. Hibernate locks include pessimistic locks and optimistic locks.

1. pessimistic lock

It refers to a conservative attitude towards data being modified by the outside world. Assume that another customer may be able to access the same data at any time. To maintain the consistency of data operations, the data is locked at the database level, it depends on the locking mechanism provided by the database.
The database locks implemented based on JDBC are as follows:

Select * from account where name = "Erica" for update

During the update process, the database is locked, and any other operations on this data will be delayed. This transaction is unlocked after being committed.
Hibernate pessimistic locks are implemented as follows:

String SQL = "query statement ";
Query query = session. createQuery (SQL );
Query. setLockMode ("object", LockModel. UPGRADE );

Here, we mention the hibernate locking mode:

Lockmode. None: No lock mechanism.
Lockmode. Write: hibernate will automatically obtain the insert and update records.
Lockmode. Read: hibernate automatically obtains the data when reading the record.

These three locking modes are used internally by Hibernate and are irrelevant to database locking:

Lockmode. Upgrade: Use the for update statement of the database to add a lock.

Here, we should note that the database lock mechanism can be used only when the lock is applied before the query starts (that is, before hive generates an SQL statement. Otherwise, the data has been loaded through an SQL statement that does not contain the for updata clause, so the so-called database locking is impossible.
However, considering the system performance, this is not a problem for a single or small system. However, if it is a system on the network, there will be a lot of connections at the same time, what should we do if hundreds or even thousands of concurrent accesses occur? If we wait until the database is unlocked before performing the following operations, what resources are wasted? -- This leads to the emergence of optimistic locks.

2. Optimistic lock

Optimistic Locking is optimistic that data access rarely occurs at the same time, so it is not locked at the database level. In order to maintain the correct data, optimistic Locking adopts the logic of the application to implement version control.

For example, if there are two clients, customer A first reads the account balance of 100 yuan, and customer B also reads the data of the account balance of 100 yuan. Customer A extracts 50 yuan, after the database is changed, the balance in the database is 50 yuan, and customer B needs to withdraw 30 yuan. According to the information obtained, the balance between and 30 will be 70, if you change the database at this time, the final balance will be incorrect.

When the pessimistic locking policy is not implemented, data inconsistency occurs. There are several solutions: update first and update later, it is complicated to check the changed data or check all attributes for Optimistic Locking.

Hibernate implements post-update based on version number check, which is also recommended by Hibernate. It adds a VERSON column record to the database to read data together with the version number, increase the version number when updating data, and then compare the version number with the version number in the database. if the version number is greater than the version number in the database, update the version number. Otherwise, an error is returned.

In the preceding example, If Customer A reads the account balance of 1000 yuan and the version number is 5, Customer B also reads the account balance of 1000 yuan, and the version number is also 5, customer A's account balance is 500 after receiving the payment. In this case, the version number is added to 1. The current version number is 6, and the database version number is 5. Therefore, after updating the database, the database balance is 500, the version number is 6, and the database needs to be changed after Customer B receives the payment. The database version number is 5, but the database version number is 6, which is not updated at this time, b. The database is changed only when customer data is re-read from the database and business processes are re-performed.

When Hibernate is used to implement version control lock, we add a version attribute to our object, for example:

Public class Account {
Private int version;
....
Public void setVersion (int version ){
This. version = version;
}
Public int getVersion (){
Return version;
}
....
}

In the image file, we use the optimistic-lock attribute to set version control, and add a <version> label after the <id> attribute bar, as shown below:

<Hibernate-mapping>
<Class name = "onlyfun. caterpillar. Account" talble = "ACCOUNT"
Optimistic-lock = "version">
<Id.../>
<Version name = "version" column = "VERSION"/>
....
</Class>
</Hibernate-mapping>

After version control is set, If Customer B tries to update the data in the preceding example, the StableObjectStateException is thrown. We can capture this exception and re-read the data in the database during processing, at the same time, the current data of Customer B and the data in the database are presented, giving Customer B the opportunity to compare the inconsistent data to determine the part to be changed, alternatively, you can design a program to automatically read new data and repeat the deduction business process until the data can be updated, which can be performed on the background without the need for your customers to know.

But optimistic locks cannot be solved: The implementation of optimistic locks is often implemented in our system based on the data storage logic in the system, updates of user balances from external systems are not controlled by our system, and illegal data may be updated to the database. Therefore, when doing e-commerce, we must pay attention to this problem and adopt reasonable logic verification to avoid data execution errors.

You can also specify the lock mode when using Session load () or lock () to lock the Session.

If the database does not support the specified locking mode, Hibernate will choose an appropriate locking replacement instead of dropping an exception.

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.