✅ Hibernate Session Lifecycle
🔹 1) Open
- You open a new
Session
from aSessionFactory
:
Session session = sessionFactory.openSession();
A new first-level cache is created, and the session is ready to interact with the database.
🔹 2) Begin Transaction (optional but recommended)
- Start a database transaction associated with the session:
Transaction tx = session.beginTransaction();
🔹 3) Perform Operations
- Perform CRUD operations inside the session:
User user = new User();
user.setUsername("john");
session.save(user); // entity becomes persistent in the session cache
User fetched = session.get(User.class, user.getId()); // served from cache or DB
fetched.setEmail("john@example.com"); // change is tracked automatically
🔹 4) Flush (automatic or manual)
- Hibernate flushes pending changes in the session cache to the database, generating SQL statements.
- This happens automatically:
- Before committing the transaction.
- Or manually if you call
session.flush()
.
🔹 5) Commit or Rollback Transaction
- Commit writes the changes permanently:
tx.commit();
Or rollback discards the changes if an error occurs:
tx.rollback();
🔹 6) Close Session
- Releases JDBC connections and destroys the first-level cache:
session.close();
🔹 Lifecycle summary diagram:
openSession() → beginTransaction() → [CRUD] → flush → commit/rollback → closeSession()
✅ Important points:
- Session is lightweight but not thread-safe → use one session per unit of work (e.g., per request).
- While the session is open, Hibernate tracks changes to persistent entities and caches them in first-level cache.
- Closing the session releases resources and evicts the first-level cache.
🔹 Example full lifecycle:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
User user = session.get(User.class, 1L); // fetch or load entity
user.setUsername("newName"); // modification tracked
tx.commit(); // flush + commit
session.close(); // releases resources
✅ Key takeaway:
The session lifecycle spans opening → transaction → CRUD → flush → commit/rollback → close, and understanding it is critical to writing efficient, bug-free Hibernate code.