You open a Hibernate session by calling openSession()
on a SessionFactory
instance. The session represents a single unit of work and serves as the main interface for CRUD operations, queries, and transaction management.
// Assume you already built a SessionFactory instance named sessionFactory
Session session = sessionFactory.openSession();
🔹 What happens when you open a session?
✅ Hibernate creates a new Session
object bound to the configured database connection.
✅ A first-level cache (session cache) is created to track entities during that session.
✅ You can then begin a transaction, perform CRUD operations, and flush/commit your changes.
🔹 Full example with transaction:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
User user = new User();
user.setUsername("john");
session.save(user);
tx.commit();
session.close();
🔹 Important notes:
- Sessions are not thread-safe → use one session per thread or per request.
- Always close sessions → closing the session releases database connections and prevents memory leaks.
🔹 In modern Spring Boot apps:
✅ You usually don’t call openSession()
manually. Instead, Spring Boot + Spring Data JPA manage sessions automatically through @Transactional
boundaries or repositories.
✅ Key takeaway:
Opening a session is as simple as sessionFactory.openSession()
, and it marks the start of a unit of work, letting you persist, query, and manage entities with Hibernate.