Search code examples
javahibernatejpahibernate-session

Hibernate first level cache - does it Sync?


I am aware of the fact that Session is first level cache used by Hibernate, and once we retrieve an entity from the session, the subsequent get calls for the same entity with same identifier is fetched from the session instead of DB, until the session is Open.

Having said that, I have a doubt regarding how hibernate syncs the first level cache with DB? Consider the following scenario

//Lets say I have created the session

Session s1 = sessionFactory.getSession();
User u1 = s1.get(User.class, 1); //Getting User with ID=1
//s1 is not yet closed

//Lets say I create some other session

Session s2 = sessionFactory.getSession();
User u2 = s2.get(User.class, 1); //Getting User with ID=1
u2.setName("Abc"); // Changed a field
s2.save(u2); // Saved the changes to DB
s2.close(); //Closed the 2nd session

//Now when I once again retrieve User with ID=1 from s1, will I get updated User?
User u3 = s1.get(User.class, 1);// Here as per my understanding cache is used

So my question is

  • Since u3 is fetched from 1st level cache, does u3 have updated value?
  • If some one directly updates DB and modifies User object when session is open, does the session sync with DB?

Thanks in advance for your time and effort on this thread


Solution

  • No, Hibernate doesn't do anything to synchronize state of the entities in session cache with the DB, unless you request it explicitly.

    Usually it's not a problem, because active work usually happens inside a transaction, and operations inside a transaction are not supposed to see changes made by other concurrent transactions (details depend on isolation level, though). So, behavior of Hibernate complements the typical semantics of transaction isolation in this case.

    There can also be situations when state of the entity need to be explicitly synchronized to reflect changes made inside the same transaction. It may be caused by bulk update queries or execution of database triggers. In this case you need to request such a synchronization explicitly by calling refresh().