Hibernate Framework Hibernate Caching 2 — Questions and Answers
Question 1: Which CacheConcurrencyStrategy is appropriate for read-only data?
- READ_ONLY (Correct answer)
- NONSTRICT_READ_WRITE
- READ_WRITE
- TRANSACTIONAL
Correct answer: READ_ONLY
READ_ONLY is the best strategy for immutable data as it offers the best performance with no lock overhead.
Question 2: What does the NONSTRICT_READ_WRITE cache strategy allow?
- Occasional stale reads in exchange for better performance (Correct answer)
- Strict consistency guarantees
- Read-only access from all threads
- Full transaction support
Correct answer: Occasional stale reads in exchange for better performance
NONSTRICT_READ_WRITE does not guarantee strict consistency, allowing brief windows of stale data for better throughput.
Question 3: How do you enable the query cache for a specific Hibernate query?
- query.setCacheable(true) (Correct answer)
- query.enableCache(true)
- query.useCache(true)
- query.cache(true)
Correct answer: query.setCacheable(true)
Calling setCacheable(true) on a Query marks its results as eligible for storage in Hibernate's query cache.
Question 4: What property must be set to enable the Hibernate query cache?
- hibernate.cache.use_query_cache=true (Correct answer)
- hibernate.query.cache=true
- hibernate.enable.query_cache=true
- hibernate.cache.query=enabled
Correct answer: hibernate.cache.use_query_cache=true
The hibernate.cache.use_query_cache property must be set to true to activate Hibernate's query result caching.
Question 5: What happens to the second-level cache when an entity is updated?
- The cached entry for that entity is invalidated (Correct answer)
- The cache is completely cleared
- Nothing happens to the cache
- The cache is written to disk
Correct answer: The cached entry for that entity is invalidated
When an entity is updated, Hibernate invalidates its specific entry in the second-level cache to prevent stale data from being served.
Question 6: Which method evicts all entities of a given class from the second-level cache?
- sessionFactory.getCache().evictEntityData(EntityClass.class) (Correct answer)
- session.clearCache(EntityClass.class)
- cache.evict(EntityClass.class)
- sessionFactory.evict(EntityClass.class)
Correct answer: sessionFactory.getCache().evictEntityData(EntityClass.class)
The evictEntityData() method on the Cache object obtained from SessionFactory removes all cached instances of a specific entity class.
Which CacheConcurrencyStrategy is appropriate for read-only data?