Middle
What levels of caching exist in Hibernate?
sobes.tech AI
Answer from AI
Hibernate supports three levels of caching:
-
First Level Cache (Session Cache):
- Cache associated with the
Sessionobject. - Enabled by default.
- Its lifecycle is tied to the
Sessionobject. - Hibernate checks this cache before executing database queries.
- If the object is found in the session cache, a copy is returned without querying the database.
- Cache associated with the
-
Second Level Cache (SessionFactory Cache):
- Optional cache shared among all
Sessions created from a singleSessionFactory. - Requires explicit configuration and cache provider selection (e.g., Ehcache, Infinispan).
- Stores objects read from the database, collections, and query results.
- Significantly improves performance when reading the same data frequently.
- Optional cache shared among all
-
Query Cache:
- Optional cache that stores not the objects themselves, but the results of queries (object identifiers).
- Requires enabling both second-level cache and the Query Cache itself.
- When executing a query, Hibernate checks if a cached result exists for that query and its parameters.
- If found, Hibernate retrieves the objects from the second-level cache or, if absent, from the database using cached identifiers.
Configuration of second-level cache in hibernate.cfg.xml:
<!-- Explicitly enable second-level cache -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<!-- Choose cache provider (e.g., Ehcache) -->
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<!-- Enable query cache -->
<property name="hibernate.cache.use_query_cache">true</property>
Annotation for entity caching:
@Entity
@Cacheable // Enables caching for this entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE) // Concurrency strategy
public class User {
// ... fields
}
Concurrency strategies for second-level cache:
| Strategy | Description |
|---|---|
NONE |
Caching is disabled. |
READ_ONLY |
Data is never modified after caching. Fastest. |
NONSTRICT_READ_WRITE |
Data can change. No guarantee of consistency during concurrent modifications from different sessions. |
READ_WRITE |
Data can change. Consistency is guaranteed. Uses locks. |
TRANSACTIONAL |
Data can change. Consistency is guaranteed within JTA transactions. |