What should the scenario to use second level cache in hibernate?

Stack over flow says :
  1. the 2nd level cache is a key-value store. It only works if you get your entities by id.
  2. the 2nd level cache is invalidated / updated per entity when an entity is updated/deleted via hibernate. It is not invalidated if the database is updated in a different way.
  3. for queries (e.g. list of customers) use the query cache.
for more details : When and how to use hibernate second level cache?
===================================
Best pics from stack :

Q. When does hibernate hit this cache?

 First Level cache is associated with the Session object. The Second Level Cache is associated with the Session Factory object. If object is not found in the first, then the second level is checked.
===================================
It doesn't work when:
  • Let's say you're writing such a query: from Author a fetch join a.books where a.id=?. Only Authors will be fetched from the cache, books will be obtained from the DB. Joins can't hit cache.
  • If in your mapping you've mentioned fetch="join", this means that joins will be used everywhere instead of separate select statements. Process level cache works on children objects only if fetch="select" is used.
  • If you don't select by ID. 2nd level cache stores a map of entities' IDs to other properties (it doesn't actually store objects, but the data itself), so if your lookup looks like this: from Authors where name = :name, then you don't hit cache.




No comments:

Post a Comment