Senior
What happens when findById is called twice with the same ID within a single Hibernate session (first-level cache)?
sobes.tech AI
Answer from AI
When two findById calls are made with the same ID within a single Hibernate session, the first-level cache (Session Cache) will be used.
The first call loads the object from the database and places it in the session cache. The second call Hibernate will not make an additional database request but will return the object from the cache.
This helps improve performance by avoiding repeated database requests within a session and ensures data integrity (the same object in memory).
Example:
Session session = sessionFactory.openSession();
MyEntity entity1 = session.find(MyEntity.class, id); // database request
MyEntity entity2 = session.find(MyEntity.class, id); // from cache, no request
session.close();