You close a Hibernate Session
by calling its close()
method:
session.close();
🔹 What happens when you call session.close()
?
✅ Releases the JDBC connection associated with the session back to the connection pool (e.g., HikariCP).
✅ Destroys the session’s first-level cache, evicting all managed entities.
✅ Cleans up other resources like prepared statements and internal caches.
✅ Marks the session as closed — trying to use it afterward will throw a org.hibernate.SessionException
.
🔹 When should you close a session?
- Always close the session after finishing a unit of work (e.g., at the end of a request or service method).
- If you don’t close it, you can leak database connections, exhaust the connection pool, or hold unnecessary memory.
🔹 Full example with proper session closure:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
try {
User user = session.get(User.class, 1L);
user.setUsername("updated_name");
tx.commit();
} catch (Exception e) {
if (tx != null) tx.rollback();
e.printStackTrace();
} finally {
session.close(); // ensures session is closed even if exceptions occur
}
🔹 In Spring Boot apps:
✅ You typically don’t call session.close()
manually → Spring manages session lifecycle automatically when you use @Transactional
.
Always call session.close()
when done to release database resources — in modern apps, Spring or other frameworks often handle this for you, but in manual setups it’s your responsibility.