Video in progress

Strong Middle 🐻 Hibernate and JPA

What is stored inside Hibernate's second-level cache, and which concurrency strategy would you choose?

Not the entity objects but their "dehydrated" state: an array of field values keyed by id. The strategies are READ_ONLY, NONSTRICT_READ_WRITE, READ_WRITE and TRANSACTIONAL. The choice depends on how much the data changes and how much staleness you can tolerate.

📖 Answer

The L1 cache (the persistence context) lives within a single session. The L2 cache is at the SessionFactory level and is shared by all sessions. What's written into it is not the entity itself but an array of values; on read, Hibernate assembles a new object from it. That's why one thread's changes don't "leak" into another through an object.

@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "currency")
public class Currency { ... }
spring.jpa.properties.hibernate:
  cache.use_second_level_cache: true
  cache.region.factory_class: jcache

Collections are cached in a separate region and store only the ids of the children. If the child entity itself isn't cached too, a SELECT still goes out for each id. This is a common gotcha.

The strategies:

  • READ_ONLY: reference data that never changes (countries, currencies). The fastest; an attempt to modify throws an error.
  • NONSTRICT_READ_WRITE: changes rarely, and a stale value may be visible for a short time.
  • READ_WRITE: puts a "soft lock" during an update, so a stale value isn't visible. The default choice in most cases.
  • TRANSACTIONAL: needs JTA and a suitable provider; rare in practice.

Limitations: with several instances, a local cache (Caffeine/Ehcache heap) is separate on each node, so a row that node A updated is still seen as old by node B. Then you need a distributed provider (Infinispan, Hazelcast) or a short TTL. If native SQL or another service changes the database, the cache doesn't know.

I put the L2 cache only on entities that are read a lot and change rarely, and I measure the hit rate with statistics.