Hibernate First-Level and Second-Level Cache

Difficulty: Advanced

Question

Explain Hibernate's first-level and second-level cache. How do they differ and what problems can caching cause?

Answer

Databases are slow compared to memory, so Hibernate tries hard not to ask the database the same question twice. It does this at two levels, and the difference between them is a favourite topic for experienced-role interviews at product companies.

The first-level cache is the persistence context, which belongs to a single Session, or in JPA terms a single EntityManager. It is always on and you cannot disable it. When you load an entity by id, Hibernate stores it in that context keyed by type and id. Ask for the same entity again inside the same session and you get the identical Java object back without any SQL. This is also what enables dirty checking: at flush time Hibernate compares the loaded snapshot with the current state and issues UPDATE statements automatically, which is why you do not need to call save on a managed entity. In Spring, the EntityManager is normally scoped to a transaction, so the first-level cache lives for the duration of a @Transactional method. Outside a transaction, or with open-in-view, its lifetime differs. Two separate transactions never share the first-level cache.

Note an important detail: the first-level cache helps for find by id and lazy association loading, but a JPQL or derived query always goes to the database. The returned rows are then reconciled with what is already in the context, so you get the existing instances, but the query still executes.

The second-level cache is different: it is optional, belongs to the SessionFactory, and is shared across all sessions and transactions in the application. It caches entity state, as disassembled data rather than objects, by id. You enable it by choosing a provider such as Ehcache, Caffeine through JCache, or Infinispan, setting hibernate.cache.use_second_level_cache=true, and marking entities with @Cache or javax-style @Cacheable. When a session misses in its first-level cache, Hibernate checks the second-level cache before hitting the database. There is also an optional query cache, enabled separately, which stores the ids returned by a query, but it is invalidated whenever the related tables change, so it suits read-mostly data only.

The danger is staleness and complexity. Cached data can be out of date if other applications or direct SQL modify the database, or in a clustered deployment with per-node caches without distributed invalidation. Hibernate manages consistency for changes it makes itself, using cache concurrency strategies such as READ_ONLY for immutable reference data, NONSTRICT_READ_WRITE, READ_WRITE, and TRANSACTIONAL. Bulk HQL updates bypass entity-level tracking. Memory pressure is another risk if you cache large volumes without eviction limits.

Good use cases are rarely changing reference data: countries, colleges, skill lists. Poor use cases are frequently updated, user-specific, or huge datasets. Many teams skip the Hibernate second-level cache entirely and use Spring's Cache abstraction with @Cacheable and Redis at the service layer, which is easier to reason about and control. State that trade-off in the interview: measure first, cache deliberately, define eviction and time-to-live, and never cache blindly.

Code examples

Observing the first-level cache and enabling second-level

@Service
@RequiredArgsConstructor
class CacheDemo {
    private final EntityManager em;

    @Transactional
    public void demo() {
        Student a = em.find(Student.class, 1L);   // SQL executed
        Student b = em.find(Student.class, 1L);   // no SQL: served from persistence context
        System.out.println(a == b);               // true, same instance

        a.setName("Updated");                     // dirty checking: UPDATE issued at commit
    }
}

@Entity
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
class College {
    @Id Long id;
    String name;
}

// application.yml
// spring.jpa.properties.hibernate.cache.use_second_level_cache: true
// spring.jpa.properties.hibernate.cache.region.factory_class: jcache
// spring.jpa.properties.hibernate.javax.cache.provider: org.ehcache.jsr107.EhcacheCachingProvider

The second find returns the same object with no SQL. College is a good second-level candidate as it is read-mostly reference data.

Key points

Common follow-up questions

Interview tips

Concepts covered

First-Level Cache, Second-Level Cache, Persistence Context, Query Cache

More Spring Boot questions