Junior — Middle
Can you explain what the Persistence Context in Hibernate is and how it works?
sobes.tech AI
Answer from AI
The Persistence Context in Hibernate is a scope within which Hibernate tracks the state of objects associated with the database. It acts as a first-level cache and manages the lifecycle of objects.
When you load an object from the database, Hibernate places it in the persistence context. All changes made to this object are automatically tracked. When flush() is called or a transaction is committed, Hibernate synchronizes the changes with the database.
Main features:
- The persistence context guarantees that within a single Hibernate session, the same instance of an object is always returned for the same database record.
- Changes to objects are automatically tracked and saved without explicitly calling update.
- The persistence context exists within the scope of a session.
Example:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
User user = session.get(User.class, 1); // load object, it is placed in the context
user.setName("New Name"); // change is tracked
tx.commit(); // changes are automatically saved to the database
session.close();