During a transaction, an error occurs after several database operations have been successfully executed. How does Hibernate ensure data integrity in this situation?

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

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.

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.

Last updated: 16 July 2026

Previous question: How do you handle a Hibernate session in a web application to ensure that it is properly closed, avoiding memory leaks?

Next question: You need to add auditing features to track changes in entity data. What Hibernate feature would you use to achieve this?

More Hibernate (Optional) interview questions

All Hibernate (Optional) questions