refresh() method in Hibernate

refresh(): It is used to synchronize database data with session data.

Lets see the importance of refresh() method with the below scenarios.

Scenario 1: One session and calling one time get() method

Employee table

Application code:

Output

Explanation

  • session.get(Employee.class, 1) hits the database and fetches the data from database and assign the data to employee entity object and this entity object is cached on session object.
  • When we update the data on the database it will not get the updated data. It just shows the session cached data. Thats the reason the updated values are not printed.

Scenario 2: One session and calling multiple times get() method

Application code:

Output

Explanation

  • When session.get(Employee.class, 1) method called second time, it will check wthether the employee object is available in session or not. If the object is there in session it will not hit the database.
  • Here employee with empno 1 is already present in the session object. That’s the reason get() method will not hit the database when we are second time.Thats the reason the updated values are not printed.

Scenario 3: Multiple sessions

Application code:

Output

Explanation

  • Here session2 dont have any associated objects. So get() method hits the database,fetches the records from database and displayed the updated records.
  • Problem is here we need to create new session object to get the updated record. Instead we can use refresh() method to get the updated records from the database.

Scenario 4: Using refresh()

Application code

Output

Explanation

  • Here after calling sessoion.refresh(employee), Hibernate compares database data and employee object data. If it finds any difference it will again execute select query and update the employee object data.

 

Posted in hibernate and tagged , , .

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">