Hibernate Two locking mechanisms are supported : 
That is to say “ Pessimistic lock (Pessimistic Locking)” and “ Optimistic lock (OptimisticLocking)”

1) Pessimistic lock : Mainly through query.setLockMode( " user " ,LockMode.UPGRADE);  //  Lock up ( Must query before ) 
, Dependent database lock mechanism Will be generated accordingly  select * from user where recordid=1 for update

2) Optimistic lock : Map file increase optimistic-lock,
Add version number field to corresponding database table , Read out the version number field together , Add the version number when updating 1, Verify that the field is updated normally if it is larger than that when it is read out , otherwise ( Overdue data )
tx.commit() Throw at StaleObjectStateException different
often , And indicates that the version check failed , The current transaction is attempting to commit an expired data . By catching this exception , I We can deal with the failure of optimistic lock verification


<class name="com.xxx.model.pay.TicketOrder" table="TICKET_ORDER" 
optimistic-lock="version" lazy="false">

<version name="version" column="ORDER_VERSION" type="integer"/>
use read-commited Mechanism available pessimistic lock   Optimistic lock to solve non-repeatable read  and  phantom-read
problem ( Pessimistic lock or optimistic lock solves the problem of non repetition and unreal reading )

The realization of pessimistic lock , Often rely on the lock mechanism provided by the database ( Only the lock mechanism provided by the database layer can guarantee the exclusive access of data , otherwise , Even if the lock mechanism is implemented in this system , There is no guarantee that the external system will not modify the data ). 
Hibernate The lock mode of is : 
Ø LockMode.NONE : No lock mechanism . 
Ø LockMode.WRITE :Hibernate stay Insert and Update It will be acquired automatically when recording . 
Ø LockMode.READ : Hibernate It will be acquired automatically when reading records . 

These three lock mechanisms are generally controlled by Hibernate Internal use , as Hibernate To ensure Update Objects will not be modified during the process , Will be in save Automatically add the WRITE lock . 

Ø LockMode.UPGRADE : Using database for update Clause lock . 
Ø LockMode. UPGRADE_NOWAIT :Oracle Specific implementation of , utilize Oracle Of for update nowait Clause implementation lock . 

 Hibernate Pessimistic lock of , It is also the realization of lock mechanism based on Database . The following code implements the locking of query records :
  Java code   
* String hqlStr  =  " from TUser as user where user.name='Erica'" ;   
* Query query  =  session.createQuery(hqlStr);   
* query.setLockMode( " user " ,LockMode.UPGRADE);  //  Lock up     
*  List userList  =  query.list(); //  Execute query     
get data  query.setLockMode  Lock the records corresponding to the specific alias in the query statement ( We are
Person Class specifies an alias “p”), That's all that's returned Person Record and lock . Observation operation period Hibernate Generated SQL sentence : 

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
  here Hibernate By using the for update Clause implements pessimistic lock mechanism . 

The above two locking mechanisms are commonly used in the application layer , Locking is also achieved by :

org.hibernate.Session.get(Class arg0, Serializable arg1, LockMode arg2)

org.hibernate.Session.lock(Object arg0, LockMode arg1)                         
org.hibernate.Query.setLockMode(String arg0, LockMode arg1)             
 //arg0 Is the alias in the query statement

org.hibernate.Criteria.setLockMode(LockMode arg1)
Java code   
* Person p = (Person)session.get(TUser.class,1,LockMode.UPGRADE);  
* System.out.println(p.getUsername());  
* Person p = (Person)session.get(TUser.class,1);  
* session.lock(p,LockMode.UPGRADE);  
* System.out.println(p.getUsername());  
* Criteria c = session.createCriteria(TUser.class);  
* c.add(Restrictions.eq("name","Erica"));  
* c.setLockMode(LockMode.UPGRADE);  
* c.list();  
be careful , Only before the query starts ( that is Hiberate generate SQL before ) Set lock , Only through the lock mechanism of the database can the lock be added , otherwise , Data has passed without for
update Clause's Select SQL Load in , There is no way to lock the database .

Optimistic lock , Mostly based on data version (Version) Record mechanism implementation . What is data version ? Add a version ID to the data , In the database table based version solution , Generally, you can add a “version” Field to implement . When reading out data , Read out this version number together , When updated later , Add one to this version number . here , Compare the version data of submitted data with the current version information recorded in the database table , If the submitted data version number is greater than the current database table version number , Update , Otherwise, it is considered as overdue data . 

1. First of all TUser Of class Descriptor add optimistic-lock attribute :
  Xml code   
* < hibernate - mapping >    
*  < class name="org.hibernate.sample.TUser"  table="t_user"  dynamic-update=
"true"  optimistic-lock="version">  
* ……   
*  </ class >    
*  </ hibernate - mapping >      

  Add a Version property descriptor  
Code content
Java code   
* <hibernate-mapping>  
*     <class name="org.hibernate.sample.TUser" table="t_user" dynamic-update=
"true" dynamic-insert="true" optimistic-lock="version">  
*         <id name="id" column="id" type="java.lang.Integer">  
*             generatorclass="native"></generator>  
*         </id>  
*         <version column="version" name="version" type="java.lang.Integer"
*     ……  
*     </class>  
* </hibernate-mapping>   
be careful version Node must appear in ID After node .

  Here we declare a version attribute , Used to store version information of users , Save in TUser Tabular version In field .
At this point, if we try to write a piece of code , to update TUser Data recorded in the table , as : 
Code content
Java code   
* criteria = session.createCriteria(TUser.class);  
* criteria.add(Expression.eq("name", "Erica"));  
* ListuserList = criteria.list();  
* TUseruser = (TUser) userList.get(0);  
* Transactiontx = session.beginTransaction();  
* user.setUserType(1); //  to update UserType field   
* tx.commit();    

Every time TUser When updating , We can find out , In the database version Are increasing . And if we try to tx.commit
before , Start another Session, Right name is Erica Use of User operation , To simulate concurrent updates : 
Code content
  Java code   
* Sessionsession = getSession();  
* Criteriacriteria = session.createCriteria(TUser.class);  
* criteria.add(Expression.eq("name", "Erica"));  
* Sessionsession2 = getSession();  
* Criteriacriteria2 = session2.createCriteria(TUser.class);  
* criteria2.add(Expression.eq("name", "Erica"));  
* ListuserList = criteria.list();  
* ListuserList2 = criteria2.list();  
* TUseruser = (TUser) userList.get(0);  
* TUseruser2 = (TUser) userList2.get(0);  
* Transactiontx = session.beginTransaction();  
* Transactiontx2 = session2.beginTransaction();  
* user2.setUserType(99);  
* tx2.commit();  
* user.setUserType(1);  
* tx.commit();  
Execute the above code , The code will be tx.commit() Throw at StaleObjectStateException different
often , And indicates that the version check failed , The current transaction is attempting to commit an expired data . By catching this exception , I We can deal with the failure of optimistic lock verification . 

Comparison between pessimistic lock and optimistic lock : 
Pessimistic lock mostly depends on the lock mechanism of database , To ensure the maximum exclusivity of the operation . But then comes the huge cost of database performance , Especially for long affairs , This kind of expense is often unbearable ; 

Compared with pessimistic lock , Optimistic locking mechanism adopts a more relaxed locking mechanism . Optimistic locking mechanism is often based on the data storage logic in the system , Therefore, it also has certain limitations , As in the example above , Because optimistic locking mechanism is implemented in our system , Updates from external systems are not controlled by our system , As a result, dirty data may be updated to the database .

In the system design stage , We should give full consideration to the possibility of these situations , And adjust accordingly ( If optimistic locking strategy is implemented in database stored procedure , Only data update channels based on this stored procedure are open to the public , Instead of exposing database tables directly to the public . 
Optimistic lock implementation is built in its data access engine . If you don't need to consider the update operation of the external system to the database , utilize Hibernate Transparent optimistic lock implementation provided , Will greatly improve our productivity . 
Hibernate Through class Descriptor's optimistic-lock Attribute combination version Descriptor assignment . 
optimistic-lock Properties have the following optional values : 
Ø none  No optimistic lock  
Ø version  Optimistic locking through version mechanism  
Ø dirty  Optimistic locking by checking the changed attributes  
Ø all   Optimistic lock by checking all properties  

Through which version The optimistic locking mechanism is Hibernate Implementation of optimistic lock recommended by the government , It's also Hibernate in , At present, the only time when the data object is detached Session Lock mechanism that is still effective in case of modification . therefore ,
Normally , We all choose version Method as Hibernate Optimistic lock implementation mechanism .

©2019-2020 Toolsou All rights reserved,
Message quality platform series | Full link troubleshooting What is? FPGA? New York Youth Project “ Recapture Wall Street ”: Safeguarding the interests of retail investors Redis Queue implementation java Second kill system , No script , It can be used in production Don't annoy the panda with any cat !「 Kung Fu Panda 」20 It's the year of man 4 blood cartoon | CPU Warfare 40 year , The real king finally appeared !JS How to operate 20 Review strategy for senior students with high marks !!! Big data tells you , How tired are Chinese women MySQL An interview is a must !