Optimistic and pessimistic locks in hibernate

Source: Internet
Author: User
Hibernate supports two types of locks: PessimisticLocking and OptimisticLocking: it refers to a conservative attitude towards the external modification of database data (whether it is the transaction processing of the system or the transaction processing of the external system ), data is locked throughout the data processing process. In hibernate

Hibernate supports two types of locks: Pessimistic Locking and Optimistic Locking: it refers to a conservative attitude towards the external modification of database data (whether it is the transaction processing of the system or the transaction processing of the external system ), data is locked throughout the data processing process. In hibernate

Hibernate supports two types of locks: Pessimistic Locking and Optimistic Locking)

Pessimistic lock: it refers to the conservative attitude towards modifying the database data by the outside world (whether it is the transaction processing of the system or the transaction processing of the external system ), data is locked throughout the data processing process. Pessimistic locks in hibernate rely on the locking mechanism in the database (because only the database layer can control the data operations of the system and external systems on the database ).

For example, "select * from user where userName = 'johnson 'for update" locks all userName = 'johnson' records in the user table. Before this transaction is committed, these records cannot be modified.

Pessimistic locks in hibernate are also implemented based on the database lock mechanism.

String hqlStr = "from TUser as user where user. name = 'lili' "; Query query = session. createQuery (hqlStr); query. setLockMode ("user", LockMode. UPGRADE); // lock List userList = query. list (); // execute the query to obtain data

In the above Code, the first parameter of setLockMode specifies the record returned when the alias is user.
The generated SQL statement 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_ where (tuser0_.name='Erica' ) for update

Hibernate implements the pessimistic lock mechanism through the for update clause in the database.
Hibernate lock 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.
The above three lock mechanisms are generally used internally by Hibernate. For example, in order to ensure that objects in the Update process are not modified by the outside world, Hibernate will automatically add the WRITE lock to the target object in the implementation of the save method.
LockMode. UPGRADE: using the database'sFor updateClause lock.
LockMode. UPGRADE_NOWAIT: the specific implementation of Oracle, which uses the Oracle for update nowait clause to implement locking.
The above two locking mechanisms are commonly used at the application layer. The locking is generally implemented through the following methods:
Criteria. setLockMode
Query. setLockMode
Session. lock

Compared with the pessimistic lock, the optimistic lock mechanism is relatively loose. Pessimistic locks are implemented by the database lock mechanism in most cases to ensure maximum exclusivity. On the other hand, the database overhead is very large, especially for long transactions.

Optimistic locks are mostly implemented based on the data version record mechanism. That is, add a version ID to the data table. When the data is read, the version ID is read together. When the data is updated, add 1 to the version ID. Compare the submitted version data with the current version information in the database. if the version number of the submitted data is greater than the current version number of the data table, update is allowed. Otherwise, the data is considered to have expired.

Hibernate has two optimistic locks: version and timestamp.

Example of Configuration:

    
              
            
                 
                   
                    
               
              
                
                  
                  
                  
              
         
    

Negative problem caused by optimistic locks: If two different transactions read one piece of data and update the data at the same time, the program reports an exception: org. hibernate. staleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect ). At this time, an exception will be caught, and an exception will be handled and the user will be reminded to submit again.
Similarly, optimistic locks have limitations. It only controls the concurrent transaction operations of the system, but the operations of the external system on the data table cannot be controlled. At this time, a solution is to implement an optimistic lock mechanism in the stored procedure, in this way, both the transaction operations of the system and the external system can be controlled by the database. Therefore, in the design phase, we should try to consider the various situations, whether the implementation is good at the program side or the database side is better.

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.