Sobes.tech
Senior

What is the first-level cache in Hibernate and how does it work?

sobes.tech AI

Answer from AI

The first-level cache (L1 Cache) in Hibernate is a session cache that exists within a single session (Session). It stores objects loaded or saved in the current session to avoid repeated database queries for the same data.

How it works:

  • When an object is loaded through a Hibernate session, it first checks the L1 cache.
  • If the object is found in the cache, it is returned without querying the database.
  • If not, a database query is executed, the object is loaded, and placed into the cache.
  • All changes to objects in the session are tracked and synchronized with the database upon calling flush().

Features:

  • The cache exists only within a single session.
  • It is not shared between sessions.
  • It helps improve performance by reducing the number of queries.

Example:

Session session = sessionFactory.openSession();
User user1 = session.get(User.class, 1); // database query
User user2 = session.get(User.class, 1); // from L1 cache, no query executed
session.close();