title: When and how to use hibernate second level cache?
body: <p>I have trouble understanding when hibernate hits the second level cache and when does it invalidate the cache.</p>
  
  <p>This is what I currently understand:</p>
  
  <ul>
  <li>Second level cache stores entities between sessions, scope is the SessionFactory</li>
  <li>You have to tell which entities to cache, no entity will get cached by default</li>
  <li>Query cache stores results of queries in the cache.</li>
  </ul>
  
  <p>What I don't understand is </p>
  
  <ul>
  <li>When does hibernate hit this cache? </li>
  <li>Let's say I've set up the second level cache but not the query caching. I want to cache my customers, there's 50000 of them. In what ways can I retrieve the customers from the cache? </li>
  <li>I assume I can get them by id from cache. That would be easy but also not worthy of caching. But what if I want to do some calculation with all my customers. Let's say I want to show a list of the customers then how would I access them? </li>
  <li>How would I get all my customers if query caching is disabled? </li>
  <li>What would happen if someone updated one of the customers? 
  
  <ul>
  <li>Would that customer get invalidated in the cache or would all customers get invalidated? </li>
  </ul></li>
  </ul>
  
  <p>Or am I thinking caching totally wrong? What would be more appropriate uses of second level cache in that case? The hibernate documentation is not at all clear how the cache works in reality. There are only instructions on how to get it set up.</p>
  
  <p><strong>Update:</strong>
  So I've come to understand that second level cache(without query cache) would be good for loading data by id's. For example I have user object that I want to check for permissions in every request in a web application. Would this be a good case to reduce database access by caching the user in the second level cache? Like I would store the user id in the session or wherever and when I need to check for permissions I would load the user by it's id and check permissions.</p>