Hibernate pessimistic lock, optimistic lock

Source: Internet
Author: User

In the process of implementing business logic, it is often necessary to guarantee the exclusivity of data access. Therefore, we need some mechanism to ensure that the data will not be modified by the outside in the course of operation, such a mechanism, in this case, the so-called "lock", that is, to our selected target data locked, so that it can not be modified by other programs.

Hibernate supports two types of locking mechanisms:

1. Pessimistic lock (pessimistic Locking)

The lock is started from the loading object. The modification process has been a lock. Until the transaction commits () is committed and then unlocked.

Session.load (Info.class, "p003", Lockoptions.upgrade);

 Public classTestpessimisticlockextendsTestCase {@Test Public voidTestLock1 () {Session session=NULL; Try{Session= Hibernateutil.getsession ();//start Locking, the following testLock2 cannot be executedsession.begintransaction (); Info Data= Session.load (Info.class, "P003", Lockoptions.upgrade); Data.setname ("1111111"); Session.gettransaction (). commit ();//after the execution is unlocked, then TestLock2 can execute        }          Catch(Exception e) {e.printstacktrace ();        Session.gettransaction (). rollback (); }        finally{hibernateutil.closesession (); }} @Test Public voidTestLock2 () {Session session=NULL; Try{Session=hibernateutil.getsession ();                        Session.begintransaction (); Info Data= Session.load (Info.class, "P003", Lockoptions.upgrade); Data.setname ("2222222");        Session.gettransaction (). commit (); }          Catch(Exception e) {e.printstacktrace ();        Session.gettransaction (). rollback (); }        finally{hibernateutil.closesession (); }    } }
2. Optimistic lock (optimistic Locking)

is not a true lock, it is a conflict detection at commit time. Compare the contents of the content with the content you just started reading, and throw an exception if there is a problem. In contrast to pessimistic locking, the optimistic locking mechanism adopts a more relaxed locking mechanism.

Pessimistic locking relies on the lock mechanism of the database in most cases, to ensure the maximum degree of exclusivity of the operation. But it comes with a lot of overhead for database performance, especially for long transactions, which are often unsustainable. The optimistic locking mechanism solves this problem to some extent. Optimistic locking, mostly based on the data version (versions) recording mechanism implementation. What is a data version? is to add a version identity to the data, which is typically done by adding a "version" field to the database table in the version solution based on the database table.

How optimistic Locks work:

When the data is read, the version number is read together, and then the version number is added one after the update. At this point, the version data of the submitted data is compared to the current version information of the database table corresponding to the record, and if the submitted version number is greater than the current version number of the database table, it is updated, otherwise it is considered to be outdated data.

Configuration:

1. Add a field version to the database table

If the version field is added to the database, you must add version to the entity class and generate a get, set method

 Public classInfoImplementsjava.io.Serializable {PrivateString Code; PrivateNation Nation; PrivateString name; PrivateBoolean sex; PrivateDate birthday; PrivateSet families =NewHashSet (0); PrivateSet works =NewHashSet (0); Private intVersion//the entity class must also have version, and generate getter and setter     Public intgetversion () {returnversion; }     Public voidSetversion (intversion) {         This. Version =version; }

2. Configure <version Name= "version" in the TSE file > Note the location of version here, it must be placed behind the ID

<?XML version= "1.0"?><!DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://www.hibernate.org/dtd/ Hibernate-mapping-3.0.dtd "><!--Generated 2017-3-11 10:12:32 by Hibernate Tools 5.2.0.CR1 -<hibernate-mapping>    <classname= "Com.itnba.maya.model.Info"Table= "Info"Catalog= "MyDB"Optimistic-lock= "Version">        <Cacheusage= "Read-only"/>         <IDname= "Code"type= "string">            <columnname= "Code"length= " the" />            <Generatorclass= "Assigned" />        </ID>        <!--Configure version, position under <id></id> -        <versionname= "Version"></version>
<Many-to-onename= "Nation"class= "Com.itnba.maya.model.Nation"Fetch= "Select"> <columnname= "Nation"length= " the" /> </Many-to-one> < Propertyname= "Name"type= "string"> <columnname= "Name"length= " the" /> </ Property> < Propertyname= "Sex"type= "Java.lang.Boolean"> <columnname= "Sex" /> </ Property> < Propertyname= "Birthday"type= "Timestamp"> <columnname= "Birthday"length= "+" /> </ Property> </class></hibernate-mapping>

Code does not change after configuration is complete

Issues caused by optimistic locking

When two different transactions read a piece of data at the same time and modify it, this time the program throws Org.hibernate.StaleObjectStateException:Row was updated or deleted by another Transaction (or Unsaved-value mapping was incorrect) exception.

There are two things here too.

One is the case of two different transactions

@Test Public voidTestTransation1 () {Session Session1=NULL; Session Session2=NULL; Try{Session1=hibernateutil.getsession (); Session2=hibernateutil.getsession (); Info Info1= Session1.load (Info.class, "P003"); Info Info2= Session2.load (Info.class, "P003"); Transaction tx1=session1.begintransaction (); Info1.setname ("2222222");          Tx1.commit (); Transaction TX2=session2.begintransaction (); Info2.setname ("11111111");          Tx2.commit (); System.out.println ("Transaction 2 Commits"); }Catch(Exception e) {e.printstacktrace (); }finally{          if(Session1! =NULL) {session1.close (); }          if(Session2! =NULL) {session2.close (); }      }  } 

Transaction 2 commits when the value of version is found to be different, this time will be thrown Org.hibernate.StaleObjectStateException:Row was updated or deleted by another Transaction (or Unsaved-value mapping was incorrect) exception.

The second case is the case of a child transaction

@Test Public voidTestTransation2 () {Session Session1=NULL; Session Session2=NULL; Try{Session1=hibernateutil.getsession (); Session2=hibernateutil.getsession (); Info Info1= Session1.load (Info.class, "P003"); Info Info2= Session2.load (Info.class, "P003"); Transaction tx1=session1.begintransaction (); Transaction TX2=session2.begintransaction (); Info2.setname ("11111111");         Tx2.commit (); Info1.setname ("2222222");    Tx1.commit (); }Catch(Exception e) {e.printstacktrace (); }finally{          if(Session1! =NULL) {session1.close (); }          if(Session2! =NULL) {session2.close (); }      }  }          

We found that the thing 2 is wrapped in transaction 1, if DIR is configured to delay loading (hibnernate default is lazy loading), this time when the transaction 1 commits, the database will be queried before the update operation.

If DIR is configured for non-lazy loading (lazy= "false"), this time the transaction 1 at the time of submission will not go to query the database, but directly commit, at the time of submission found version mismatch, Thus also thrown Org.hibernate.StaleObjectStateException:Row was updated or deleted by another transaction (or Unsaved-value Mappin G was incorrect) exception.

Solutions

1, catch Staleobjectstateexception exception, prompt data outdated has been modified, let the user resubmit

2, as far as possible from the business to reduce the transaction block, the larger the transaction block, the optimistic lock caused by the problem of greater probability

Hibernate pessimistic lock, optimistic lock

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.