Thursday, 18 April 2019

What is version checking in Hibernate ?

version checking used in hibernate when more then one thread trying to access same data.
For example :
User A edit the row of the TABLE for update ( In the User Interface changing data - This is user thinking time)
and in the same time User B edit the same record for update and click the update.
Then User A click the Update and update done. Chnage made by user B is gone.

In hibernate you can perevent slate object updatation using version checking.


Check the version of the row when you are upding the row.
Get the version of the row when you are fetching the row of the TABLE for update.
On the time of updation just fetch the version number and match with your version number ( on the time of fetching).

This way you can prevent slate object updatation.

Steps 1:
Declare a variable "versionId" in your Class with setter and getter.

public class Campign { 
private Long versionId; 
private Long campignId; 
private String name; 
public Long getVersionId() { 
return versionId; 
} 
public void setVersionId(Long versionId) { 
this.versionId = versionId; 
} 

public String getName() { 
return name; 
} 
public void setName(String name) { 
this.name = name; 
} 

public Long getCampignId() { 
        return campignId; 
    } 
private void setCampignId(Long campignId) { 
        this.campignId = campignId; 
    } 

} 

Step 2. 
In the .hbm.xml file 

<class name="beans.Campign" table="CAMPIGN" optimistic-lock="version"> 

<id name="campignId" type="long" column="cid"> 
<generator class="sequence"> 
<param name="sequence">CAMPIGN_ID_SEQ</param> 

</generator> 
     </id> 
    <version name="versionId" type="long" column="version" /> 

<property name="name" column="c_name"/> 

</class> 



Step 3. 
Create a coulmn name "version" in the CAMPIGN table. 

Step 4. 
In the code 

// foo is an instance loaded by a previous Session 
session = sf.openSession(); 
int oldVersion = foo.getVersion(); 
session.load( foo, foo.getKey() ); 
if ( oldVersion!=foo.getVersion ) throw new StaleObjectStateException(); 
foo.setProperty("bar"); 
session.flush(); 
session.connection().commit(); 
session.close(); 


You can handle StaleObjectStateException() and do what ever you want. 
You can display error message. 

Hibernate autumatically create/update the version number when you update
/insert any row in the table.

Spring Boot @ConfigurationProperties and Properties File

 In this tutorial, you will learn to use @ConfigurationProperties to map properties files to POJO classes in Spring Boot application. Let’s ...