I have trouble understanding when hibernate hits the second level cache and when does it invalidate the cache.
This is what I currently understand:
- Second level cache stores entities between sessions, scope is the SessionFactory
- You have to tell which entities to cache, no entity will get cached by default
- Query cache stores results of queries in the cache.
What I don't understand is
- When does hibernate hit this cache?
- 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?
- 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?
- How would I get all my customers if query caching is disabled?
- What would happen if someone updated one of the customers?
- Would that customer get invalidated in the cache or would all customers get invalidated?
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.
Update: 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.