What this animation explains
L1 reuse reduces database requests only while the relevant object remains managed.

MODULE 3 · TOPIC 5 · VISUAL JPA & HIBERNATE LAB
Caching reduces repeated database requests by reusing state. The first-level persistence context is intrinsic to an EntityManager; second-level caching is optional, shared through an EntityManagerFactory and configured using a compatible external cache provider. Query caching is separate and optional. Cache hits are not a guarantee of freshness across external database writes; understand invalidation, concurrency and read patterns before enabling shared caching.
Browser-based JPA and Hibernate simulations. Change inputs and trace entity state, SQL, database rows and transactions. No real Java or database operations are executed.
A persistence context guarantees identity reuse for an existing entity. A repeat find for the same identifier can return the managed instance without another SQL query. Clearing detaches the entities and removes identity-map entries. The lab assumes L2 cache disabled.
Why this example? Change repeat count and context-clearing behavior to compare SQL count.
Arrows show the actual route; blue identifies the current node. Green indicates visited operations; red nodes show errors or rejected paths.
Change inputs and step through the example. SQL is illustrative; actual Hibernate SQL, timing and dialect vary. Reproduce using the real setup described in the worked examples.
L1 reuse reduces database requests only while the relevant object remains managed.
Try five lookups without clear, then clear after each lookup.
L2 caching is optional and configured at factory scope. It can supply entity state to a new persistence context. L1 is checked first; an L2 hit avoids a database SELECT for the entity in this simplified case. Eviction forces a reload if no L1 entry exists.
Why this example? Toggle L2 and evict its entry before the second context reads.
Arrows show the actual route; blue identifies the current node. Green indicates visited operations; red nodes show errors or rejected paths.
Change inputs and step through the example. SQL is illustrative; actual Hibernate SQL, timing and dialect vary. Reproduce using the real setup described in the worked examples.
L2 state reuse crosses context boundaries without sharing a managed object instance.
Compare configured cache with eviction and disabled cache.
The usual identifier-load path checks the persistence context, then an eligible shared cache, and finally the database. A cache hit is about where entity state came from; associations may still require loading separately.
Why this example? Select which context is used and whether the shared entry exists. Follow the actual branching route.
Arrows show the actual route; blue identifies the current node. Green indicates visited operations; red nodes show errors or rejected paths.
Change inputs and step through the example. SQL is illustrative; actual Hibernate SQL, timing and dialect vary. Reproduce using the real setup described in the worked examples.
Different cache layers serve different scopes; SQL is the fallback.
Choose new context with no shared entry, then select same context.
A managed object can be stale when another transaction updates the row. A repeat find inside the same context need not reload it. refresh reloads state and may overwrite local changes. The lab assumes the external update has committed and a transaction isolation level that permits the refreshed row to be seen.
Why this example? Toggle an external SQL update and refresh to compare object and database values.
Arrows show the actual route; blue identifies the current node. Green indicates visited operations; red nodes show errors or rejected paths.
Change inputs and step through the example. SQL is illustrative; actual Hibernate SQL, timing and dialect vary. Reproduce using the real setup described in the worked examples.
Cache coherence must be handled deliberately when database access bypasses Hibernate.
Enable external update and keep the context, then refresh.
Hibernate query caching is separate from entity caching and must be enabled and opted into for the query. Cached query results depend on the query and parameters, and are subject to invalidation. Entity-result layout and extra entity loads depend on Hibernate version and cache settings; the scalar query here avoids that ambiguity.
Why this example? Change the second parameter and query-cache mode; compare cache key match and SELECT count.
Arrows show the actual route; blue identifies the current node. Green indicates visited operations; red nodes show errors or rejected paths.
Change inputs and step through the example. SQL is illustrative; actual Hibernate SQL, timing and dialect vary. Reproduce using the real setup described in the worked examples.
Changing a query parameter can produce a different cache entry even when the JPQL text is unchanged.
Run threshold 60 twice with cache on, then change it to 80.
Hibernate cache concurrency strategies describe how shared cached state is coordinated with writes. READ_ONLY suits immutable reference data. READ_WRITE requires a compatible provider and coordinates updates, but is not a replacement for transaction isolation or version locking.
Why this example? Choose strategy and workload to evaluate suitability before enabling cache.
Arrows show the actual route; blue identifies the current node. Green indicates visited operations; red nodes show errors or rejected paths.
Change inputs and step through the example. SQL is illustrative; actual Hibernate SQL, timing and dialect vary. Reproduce using the real setup described in the worked examples.
Cache strategy must match the data mutation pattern.
Try READ_ONLY with mutable student marks; then select reference data.
Refer to these APIs and settings while building the real JPA project. Use a transaction for write operations.
| API / setting | Why and when to use it |
|---|---|
| em.find(Student.class,id) | Check identity map before database load |
| em.clear() | Detach all managed entities |
| em.refresh(entity) | Reload from database |
| emf.getCache().evict(Student.class,id) | Evict shared cache data for an entity ID |
| @Cacheable | Declare entity cache eligibility depending on shared-cache mode |
| hibernate.generate_statistics | Collect Hibernate statistics for diagnosis |
Follow these procedures with the Jakarta Persistence 3.1 / Hibernate ORM 6.6 teaching project. Snippets require the indicated entities and an open EntityManager; SQL varies by dialect.
Student a=em.find(Student.class,101L); Student b=em.find(Student.class,101L); System.out.println(a==b); em.clear(); Student c=em.find(Student.class,101L); System.out.println(a==c);
var sf=emf.unwrap(org.hibernate.SessionFactory.class);
var stats=sf.getStatistics();
stats.setStatisticsEnabled(true);
emf.getCache().evict(Student.class);
stats.clear();
try(var a=emf.createEntityManager()) {a.find(Student.class,101L);}
try(var b=emf.createEntityManager()) {b.find(Student.class,101L);}
System.out.println(stats.getSecondLevelCacheHitCount());
System.out.println(stats.getSecondLevelCacheMissCount());
System.out.println(stats.getPrepareStatementCount());Try answering these questions, then expand each answer and repeat the appropriate simulation.
No. It detaches entities from that EntityManager only.
No. Each creates its own managed instance from cached state.
They bypass Hibernate cache invalidation. Evict affected entries or use an appropriate consistency strategy.
Use the H2 lab, enable hibernate.generate_statistics=true and compare repeated find calls in one context and two contexts. For L2 experiments configure a compatible cache provider and cacheable entity before running actual code.
Edit this practice scratchpad and copy it into your real Java project. The browser does not compile arbitrary Java.
The L2 and query cache experiments assume a configured Hibernate-compatible provider, cacheable data and ideal sequential access with no eviction unless specified. Actual hit counts depend on mapping, cache mode, query-cache layout, invalidation, fetch plans and provider. No external cache is required for the browser labs.