Standard Session and Transaction Handling Pattern

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

Detailed Explanation

1. Getting a Session

Session session = getFactory().getCurrentSession();

2. Beginning a Transaction

Transaction tx = session.beginTransaction();

3. Performing Database Operations

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

4. Committing the Transaction

tx.commit();