Menu

First-Level and Second-Level Cache

First-Level and Second-Level Cache

Two Levels

Hibernate caches entities at two levels, and they differ in scope.

 

First-level cache

Second-level cache

ScopeOne sessionThe whole SessionFactory
DefaultAlways onOff until a provider is set up
PurposeOne object per row within a sessionShare entities between sessions

The first-level cache is the persistence context from Lesson 6. It cannot be disabled.

Enabling the Second-Level Cache

Hibernate needs a cache provider. The usual route is the org.hibernate.orm:hibernate-jcache module together with a JCache provider such as Ehcache 3. Its version must match hibernate-core.  

hibernate.cache.use_second_level_cache=true
hibernate.cache.region.factory_class=jcache
@Entity
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Country {
    @Id
    private Long id;
    private String name;
}

Code Explanation:

  • The first property enables the second-level cache, and the second selects the JCache provider.
  • @Cacheable from Jakarta Persistence marks the entity as cacheable.
  • @Cache from Hibernate sets the concurrency strategy. READ_WRITE is a safe general choice, and READ_ONLY suits data that never changes.
  • A find() on Country now checks the session first, then the shared cache, and only then the database.

Hibernate Tutorial

AP

Abhishek Pati



Learn via Video Course

Java Programming ( Telugu) Logo

Java Programming ( Telugu)

11 hrs



Get in Touch For Details