Sobes.tech
Middle

What is caching in Hibernate?

sobes.tech AI

Answer from AI

Hibernate caching is a mechanism for storing data in memory to reduce the number of database queries, thereby improving application performance.

Hibernate supports three levels of caching:

  1. First-Level Cache:

    • Enabled by default and associated with the Session object.
    • Caches objects loaded within the current session.
    • Objects are removed from the cache when the session is closed.
  2. Second-Level Cache:

    • Shared across multiple sessions (SessionFactory).
    • Requires explicit configuration and selection of a cache provider (e.g., Ehcache, Infinispan).
    • Allows caching of object data, queries, and collections.
  3. Query Cache:

    • Caches query results and their parameters.
    • Works in conjunction with the second-level cache, storing object identifiers from query results.
    • Must be explicitly enabled for each query.

Example of enabling second-level cache for an entity and a query:

// Entity annotation
@Entity
@Cacheable // Enable caching
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE) // Cache management strategy
public class User {
    // ... entity fields
}
// Enable cache for a query
Query query = session.createQuery("FROM User WHERE isActive = :active");
query.setParameter("active", true);
query.setCacheable(true); // Enable query caching
List<User> activeUsers = query.list();

Strategies for managing parallel access to the second-level cache:

Strategy Description
NONE Caching is disabled.
READ_ONLY Used for data that does not change. Fast.
NONSTRICT_READ_WRITE Suitable for data that rarely changes. No locks during read.
READ_WRITE Suitable for data that changes frequently. Requires lock management.
TRANSACTIONAL Used for data in a transaction-safe environment.
What is caching in Hibernate? — Java - sobes.tech