title: Hibernate first level cache - does it Sync?
body: <p>I am aware of the fact that <code><a href="http://docs.jboss.org/hibernate/orm/3.5/javadoc/org/hibernate/Session.html" rel="noreferrer">Session</a></code> is first level cache used by <strong>Hibernate</strong>, and once we retrieve an entity from the <code>session</code>, the subsequent get calls for the <em>same entity</em> with <em>same identifier</em> is fetched from the <code>session</code> instead of DB, until the <code>session</code> is <em>Open</em>.</p>
  
  <p>Having said that, I have a doubt regarding how hibernate syncs the first level cache with DB? Consider the following scenario</p>
  
  <pre><code>//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
  </code></pre>
  
  <p>So my question is</p>
  
  <ul>
  <li>Since <code>u3</code> is fetched from 1st level cache, does <code>u3</code> have updated value? </li>
  <li>If some one directly updates DB and modifies User object when session is open, does the <code>session</code> sync with DB?</li>
  </ul>
  
  <p>Thanks in advance for your time and effort on this thread</p>