javadatabasehibernatejpatransactions

Why should i rollback after failed commit


Why should i rollback after failed commit? In case, if commit failed, a DB won't get changes anyway. So why should i call rollback this case?


Solution

  • Let's take Oracle transaction management documentation which applies to other database engines as well:

    A transaction ends when it is committed or rolled back, either explicitly with a COMMIT or ROLLBACK statement or implicitly when a DDL statement is issued.

    Without specifying the COMMIT/ROLLBACK you may end up with the following situations:

    • A user disconnects from Oracle Database. The current transaction is committed.

    • A user process terminates abnormally. The current transaction is rolled back.

    Database transaction management is based on transaction logging:

    1. The state transition from old to new is recorded in a redo log.
    2. The state transition from new to old is recorded in an undo log.

    Because of transaction isolation requirements the data is changed against the actual table structures and it's the locking mechanism that prevents other transactions from seeing uncommitted changes. The actual data is changed because the current transaction needs to read its own writes during the transaction lifespan.

    So the actual data is changed but because we have both redo and undo logs we can easily commit/rollback or even rollback in-doubt distributed transactions that were successfully committed against a given data source, while the global transaction has failed because other enlisted data source has rolled back.

    Rolling back consists in undoing all data changes recorded by the current uncommitted transaction, so you should ROLLBACK if the current transaction has failed.