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, doesu3
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