Hibernate preserves data integrity during a failed transaction by rolling back every change made since the transaction began, so a mid-transaction error never leaves the database in a partially-updated state.
Key Points: • Hibernate delegates the actual rollback to the underlying database transaction (JDBC) or to JTA when running in a distributed/managed environment. • All operations performed through the Session within that transaction's boundary are undone together — it's all-or-nothing. • Catching the exception and calling Transaction.rollback() explicitly is the typical pattern outside container-managed transactions. • After a rollback, the Session is typically left in an unusable state and should be closed and a new one opened. • Combined with proper isolation levels, this rollback behavior prevents other transactions from ever seeing the intermediate, broken state.
Example: If a batch job updates ten Invoice rows and the sixth update violates a database constraint, wrapping the whole batch in one transaction ensures Hibernate rolls back all ten changes, so the database still reflects the pre-batch state rather than five updated and five untouched rows.
Code Example:
Transaction tx = session.beginTransaction();
try {
// multiple session.save()/update() calls
tx.commit();
} catch (Exception e) {
tx.rollback();
throw e;
} finally {
session.close();
}Interview Tip: A concise interview answer is:
"Hibernate wraps operations in a transaction, and if any operation fails before commit, it rolls back everything done since the transaction started using the underlying JDBC or JTA transaction — so partial writes never get persisted, which is what keeps the data consistent."