– notes, snippet codes, and my journal

Hibernate : Understanding First level and Second level cache

leave a comment »

found this article, a good article and easy explanation tutorial 🙂

note :

  • SessionFactory provides session, session maintains cache.
  • How will session cache object get update from DB if any changes happen. Will get update automatically or explicitily.?

In case of single session, your application code always update this cache object so it is always updated. Hibernate takes care of synchronizing the changes with database at time of flushing the session.

Now consider another example:

machine 1: reads the data and returns it for editing somewhere else
machine 2: also reads the data for modification
machine 1: updates the data and commits.
machine 2: tries to do an update and commit.

What will happen when the second machine tries to commit its changes? Hibernate will see that the data has changed while machine 2 was working on the data. That is, machine 2’s update is on stale data. Hibernate can’t always merge the two changes (nor is that always desired behaviour), so it rejects the second update by throwing org.hibernate.StaleObjectStateException.

The simplest solution, perhaps, is to add a version field using @Version on your data objects. Hibernate will automatically maintain the “version” of the data. Whenever an update takes place, the version will be changed automatically by Hibernate. Your job is the check that the version hasn’t changed between when you read the data and when you update the data. If they don’t match, you can do something to handle the problem (i.e. tell the user). There are some more sophisticated techniques for preventing concurrent updates, but this is the simplest.


Written by snippetjournal

November 24, 2014 at 3:33 am

Posted in Collection Link, Programming

Tagged with ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: