The following pattern represents the best practice for handling Hibernate sessions and transactions in your application code. This pattern ensures proper resource management and exception handling.
// 1. Get Session from SessionFactory
Session session = getFactory().getCurrentSession();
// 2. Begin a Transaction
Transaction tx = session.beginTransaction();
try {
// 3. Perform database operations
// Example operations:
// session.save(entity);
// session.update(entity);
// session.get(Entity.class, id);
// session.createQuery("from Entity").getResultList();
// ... your business logic here ...
// 4. Commit the Transaction
tx.commit();
// At this point:
// - All changes are synchronized with the database
// - The session is automatically closed (when using getCurrentSession)
} catch (RuntimeException e) {
// 5. Handle exceptions by rolling back the Transaction
if (tx != null) {
tx.rollback();
}
// Re-throw the exception to the caller
throw e;
}
// Note: When using getCurrentSession(), you don't need a finally block to close the session
// as it's automatically closed after commit/rollback
Session session = getFactory().getCurrentSession();
getCurrentSession()
: Returns the current session bound to the contextopenSession()
: Creates a new session (must be explicitly closed)getCurrentSession()
when possible as it handles session closing automaticallyTransaction tx = session.beginTransaction();
This is where you add your business logic and database operations:
// --- CREATE Operation ---
User user = new User("john", "[email protected]");
session.persist(user); // Saves the new user to the database
// --- READ Operation ---
User existingUser = session.get(User.class, 1L); // Retrieves a user by primary key (id = 1)
// --- UPDATE Operation ---
existingUser.setEmail("[email protected]"); // Hibernate tracks changes (automatic dirty checking)
// No explicit update call needed — changes are persisted on tx.commit()
// --- DELETE Operation ---
session.remove(existingUser); // Marks the entity for deletion
// --- QUERY Operation ---
List<User> users = session.createQuery("from User", User.class).getResultList(); // Retrieves all users
tx.commit();
getCurrentSession()
, automatically closes the session