Hibernate Cache - Types
|
first-level cache |
|
|---|---|
|
second-level cache |
|
|
query-level cache |
|
Hibernate Cache - When an Entity is Looked up By its ID
When an entity instance is looked up by its id (either by application logic or by Hibernate internally, e.g. when it loads associations to that entity from other entities), and second-level caching is enabled for that entity, the following happens:
- If an instance is already present in the first-level cache, it’s returned from there.
- If an instance isn’t found in the first-level cache, and the corresponding instance state is cached in the second-level cache, then the data is fetched from there and an instance is assembled and returned.
- Otherwise, the necessary data are loaded from the database and an instance is assembled and returned.
Once the instance is stored in the persistence context (first-level cache), it’s returned from there in all subsequent calls within the same session until the session is closed, or the instance is manually evicted from the persistence context. The loaded instance state is also stored in the L2 cache if it wasn’t already there
First-Level Cache
- Hibernate First Level cache is enabled by default, there are no configurations needed for this.
- We can use the session
evict()method to remove a single object from the hibernate first-level cache. - We can use the session
clear()method to clear the cache i.e to delete all the objects from the cache. - We can use the session
contains()method to check if an object is present in the hibernate cache or not, if the object is found in the cache, it returns true, or else it returns false. - Since Hibernate caches all the objects into a first-level cache. Then during bulk queries or batch updates, it’s necessary to clear the cache at certain intervals to avoid memory issues