Return to site

🗄️☕ HOW HIBERNATE STORES SECOND-LEVEL CACHE ENTRIES inspired by Java Champion Vlad Mihalcea

· jakartaee

Hibernate’s second-level cache does NOT store complete Java object graphs.

It stores entity state in a relational, disassembled form that closely mirrors the database. 🔍

🔸 TL;DR

A cache entry typically contains:

▪️ A key identifying the entity type and ID

▪️ A tuple of persistent attribute values

▪️ Foreign keys for associated entities

▪️ Version information when applicable

Associations are not materialized as complete objects inside the entity entry.

🔸 FROM ENTITY TO CACHE ENTRY

When Hibernate loads an entity, it hydrates the JDBC ResultSet into an array of values.

Before caching it, Hibernate disassembles this state:

Post {
 id = 1,
 name = "Hibernate Master Class"
}

Conceptually becomes:

Key: Post#1
State: ["Hibernate Master Class"]

The cache stores the entity’s DATA, not the managed Java object itself.

🔸 WHAT ABOUT ASSOCIATIONS?

Consider a comment linked to a post:

@ManyToOne
private Post post;

Its cache entry may resemble:

Key: Comment#2
State: [postId=1, review="Good post!"]

Hibernate stores the associated entity’s identifier, not the entire Post.

Likewise, a Post entry does not automatically embed all its comments or its one-to-one details.

🔸 WHY NORMALIZED DATA?

This model makes writes more manageable.

Updating one entity generally affects its corresponding entity cache entry instead of requiring Hibernate to locate and rewrite many duplicated aggregate representations. ✍️

The trade-off is that Hibernate cannot reconstruct a complete entity graph from one entry. Associations and cached collections must be resolved separately.

🔸 CONCURRENCY MATTERS

Because the cache mirrors relational state, Hibernate provides concurrency strategies such as:

▪️ READ_ONLY

▪️ NONSTRICT_READ_WRITE

▪️ READ_WRITE

▪️ TRANSACTIONAL

The right choice depends on how often the data changes and how strong your consistency guarantees must be. ⚖️

🔸 TAKEAWAYS

▪️ The second-level cache is shared across sessions.

▪️ It stores disassembled persistent state, not entity objects.

▪️ Associations are usually represented by identifiers.

▪️ Entity graphs are not stored as single aggregated entries.

▪️ Normalization favors targeted updates and consistency.

▪️ Cache configuration is always a performance-versus-consistency decision.

The second-level cache is not a magical copy of your domain model.

It is much closer to a cached representation of your relational data. 💡

#Java #Hibernate #JPA #Caching #Database #Performance #BackendDevelopment #SoftwareArchitecture

Go further with Java certification:

Java👇

Spring👇

SpringBook👇

JavaBook👇