Video in progress
What is the second-level cache and how does it differ from the first-level cache?
The second-level cache lives at the SessionFactory level and is shared by all sessions. It is off by default and needs a separate provider (for example Ehcache or Caffeine through JCache) and explicit opt-in per entity.
📖 Answer
A comparison:
| 1st level | 2nd level | |
|---|---|---|
| Scope | one session | the whole application (one JVM or a cluster) |
| Default | always on | off |
| What it stores | the objects themselves | the "dehydrated" state (field values) |
Enabling it:
spring.jpa.properties.hibernate.cache.use_second_level_cache=true
spring.jpa.properties.hibernate.cache.region.factory_class=jcache
@Entity
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Country { ... }
When it helps: data that rarely changes and is read a lot, such as countries, currencies and settings.
When it hurts: tables that change often or that other systems also write to directly. Hibernate doesn't know about outside changes and serves stale data. If you run several instances, the cache must be distributed or the TTL must be short.
There is also a separate "query cache" for query results, and it is enabled separately too.
Sign up to mark studied questions and save your progress.