MODULE 3 · TOPIC 5 · VISUAL JPA & HIBERNATE LAB

Caching with Hibernate and JPA

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.

1. First-level cache — repeated find calls

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.

Java / JPA code
SQL / simulation outputConsole
Data operationsCompact blocks
CurrentResultError / rejected
Why this step happens
See all steps in this scenario

    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.

    What this animation explains

    L1 reuse reduces database requests only while the relevant object remains managed.

    Try and observe

    Try five lookups without clear, then clear after each lookup.

    2. Second-level cache — cross-context 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.

    Java / JPA code
    SQL / simulation outputConsole
    Data operationsCompact blocks
    CurrentResultError / rejected
    Why this step happens
    See all steps in this scenario

      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.

      What this animation explains

      L2 state reuse crosses context boundaries without sharing a managed object instance.

      Try and observe

      Compare configured cache with eviction and disabled cache.

      3. Cache lookup hierarchy — L1, L2 and database

      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.

      Java / JPA code
      SQL / simulation outputConsole
      Data operationsCompact blocks
      CurrentResultError / rejected
      Why this step happens
      See all steps in this scenario

        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.

        What this animation explains

        Different cache layers serve different scopes; SQL is the fallback.

        Try and observe

        Choose new context with no shared entry, then select same context.

        4. Stale managed state — refresh after external writes

        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.

        Java / JPA code
        SQL / simulation outputConsole
        Data operationsCompact blocks
        CurrentResultError / rejected
        Why this step happens
        See all steps in this scenario

          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.

          What this animation explains

          Cache coherence must be handled deliberately when database access bypasses Hibernate.

          Try and observe

          Enable external update and keep the context, then refresh.

          5. Query cache — parameters and result keys

          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.

          Java / JPA code
          SQL / simulation outputConsole
          Data operationsCompact blocks
          CurrentResultError / rejected
          Why this step happens
          See all steps in this scenario

            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.

            What this animation explains

            Changing a query parameter can produce a different cache entry even when the JPQL text is unchanged.

            Try and observe

            Run threshold 60 twice with cache on, then change it to 80.

            6. Cache concurrency strategy — read-only versus read-write

            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.

            Java / JPA code
            SQL / simulation outputConsole
            Data operationsCompact blocks
            CurrentResultError / rejected
            Why this step happens
            See all steps in this scenario

              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.

              What this animation explains

              Cache strategy must match the data mutation pattern.

              Try and observe

              Try READ_ONLY with mutable student marks; then select reference data.

              API and configuration reference

              Refer to these APIs and settings while building the real JPA project. Use a transaction for write operations.

              API / settingWhy 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
              @CacheableDeclare entity cache eligibility depending on shared-cache mode
              hibernate.generate_statisticsCollect Hibernate statistics for diagnosis

              Worked practical examples

              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.

              1. Compare first-level SQL counts

              Procedure

              1. Use the H2 project. Seed a row and create a fresh EntityManager.
              2. Set hibernate.show_sql=true and ensure L2 is disabled.
              3. Find the same ID twice, clear and find again. Inspect SQL and reference comparison.
              Code / configuration
              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);
              Expected result: First comparison true, second false; the lookup after clear normally runs SQL in this controlled setup.

              2. Diagnose optional second-level cache

              Procedure

              1. For a real L2 lab install a compatible cache provider and configure its region factory, then mark Student cacheable and use a suitable cache strategy.
              2. Enable Hibernate statistics; seed data, evict Student region and reset statistics.
              3. Load ID 101 in one context and close it; load again in a new context.
              4. Compare hit, miss and SQL counts; then evict and repeat.
              Code / configuration
              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());
              Expected result: If the entity is eligible and the provider stores it, the second lookup may be an L2 hit. Inspect actual statistics instead of assuming a hit.

              Predict the outcome before you run

              Try answering these questions, then expand each answer and repeat the appropriate simulation.

              1. Does clear evict the second-level cache?

              No. It detaches entities from that EntityManager only.

              2. Are two EntityManagers guaranteed to return the same Java instance via L2?

              No. Each creates its own managed instance from cached state.

              3. Why can external SQL writes cause stale shared cache data?

              They bypass Hibernate cache invalidation. Evict affected entries or use an appropriate consistency strategy.

              Hands-on practice and assessment

              Programming challenge

              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.

              Quick assessment

              Key points and real Hibernate notes

              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.