Java.Hibernate.Beginner.How does first-level cache work by default?

How does the first-level cache work by default in Hibernate?

Answer:
The first-level cache is Hibernate’s mandatory, built-in mechanism for tracking entities within a single Session. Here’s exactly how it works by default:

🔹 Always enabled

  • First-level cache is always active — you don’t need to configure or enable it.
  • You cannot disable it: every Hibernate Session includes it automatically.

🔹 Scope: one Session

  • Cache lifetime is tied to the Session.
  • When the session is closed or cleared, the cache is destroyed.

🔹 Caching loaded entities

  • When you call session.get() or session.load(), Hibernate:
    • Checks the first-level cache first.
    • If the entity is not in the cache, it queries the database and stores the entity in the cache.
  • Any further calls for the same entity ID during the same session return the cached instance, skipping additional SQL queries.

Example:

Session session = sessionFactory.openSession();
session.beginTransaction();

User u1 = session.get(User.class, 1L); // DB query + caches entity
User u2 = session.get(User.class, 1L); // No DB query — returns u1 from cache!

System.out.println(u1 == u2); // true — same object instance from first-level cache

session.getTransaction().commit();
session.close();

🔹 Tracks entity changes

  • Hibernate uses the first-level cache to track modifications to entities.
  • When you change a persistent entity’s state, Hibernate marks it as “dirty” and writes updates to the database on flush() or commit().

🔹 Manages object identity

  • Within a session, every entity with the same primary key corresponds to exactly one object instance in the first-level cache → ensures consistency.

🔹 Eviction and clearing

  • You can remove entities from the cache manually:
session.evict(entity); // evicts one entity
session.clear();       // evicts all entities in the session

Eviction forces Hibernate to reload entities from the database next time you query them.

Key takeaway:
By default, the first-level cache:
✅ Is always enabled
✅ Works within a single session
✅ Tracks and caches entities you load or save
✅ Prevents redundant SQL queries
✅ Ensures consistent object identity and automatic change tracking.

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.