You manage transactions in Hibernate using the Transaction
API. You:
- Begin a transaction with
session.beginTransaction()
. - Commit it with
transaction.commit()
. - Optionally roll it back with
transaction.rollback()
in case of errors.
🔹 Basic example of transaction management:
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction(); // start transaction
User user = new User();
user.setUsername("john");
session.save(user); // persist entity within transaction
tx.commit(); // commit transaction (flushes changes to DB)
} catch (Exception e) {
if (tx != null) tx.rollback(); // rollback on error
e.printStackTrace();
} finally {
session.close(); // always close session
}
🔹 What happens during this flow:
✅ session.beginTransaction()
creates a new transaction bound to the current session and underlying database connection.
✅ All changes (INSERT, UPDATE, DELETE) are queued during the transaction.
✅ tx.commit()
flushes pending changes to the database and commits the transaction atomically.
✅ If an exception occurs, tx.rollback()
undoes all pending changes.
🔹 Why transactions matter:
- Without transactions, partial updates could leave your database in an inconsistent state.
- Transactions ensure atomicity, consistency, isolation, and durability (ACID properties).
🔹 In Spring Boot apps:
✅ You typically don’t call beginTransaction()
or commit()
manually → use @Transactional
, and Spring manages transactions automatically.
✅ Key takeaway:
To manually manage transactions in Hibernate:
1️⃣ session.beginTransaction()
to start,
2️⃣ perform your operations,
3️⃣ transaction.commit()
to save, or transaction.rollback()
on errors,
4️⃣ and always session.close()
to clean up.