JDBC Transaction in Java: Commit, Rollback, and Savepoint Explained with Flowchart

JDBC Transaction in Java

A JDBC transaction is a set of SQL operations executed as a single atomic unit.
All the SQL queries inside a transaction must either succeed together or fail together. If any query fails, the entire transaction is rolled back to maintain data consistency.

🔹 Key Concepts

Transaction Success:

  • All SQL queries in the transaction execute successfully → Commit the transaction.

Transaction Failure:

  • If any SQL query fails → Rollback the entire transaction.

3. Auto-Commit Mode:

  • By default, JDBC connections run in auto-commit mode.
  • In auto-commit mode, each SQL query is committed immediately after execution.

4. Manual Transaction Control:

To manage transactions manually:
connection.setAutoCommit(false); // Disable auto-commit
  • true → Enable auto-commit
  • false → Disable auto-commit

🔹 Commit & Rollback Methods

            Method.                          Purpose.                                                 Provided By
  • commit().   Saves all SQL queries executed in the transaction.    Connection interface (DB vendor implementation)
  • rollback().          Reverts all changes made in the transaction.       Connection interface
  • rollback(Savepoint savepoint).   Reverts changes up to a specific save point.  Connection interface
  • setSavepoint().   Creates a savepoint for partial rollback.   Connection interface

🔹 Flow of JDBC Transaction

/* Transaction Start */
try {
    // SQL Query 1
    // SQL Query 2
    // SQL Query 3
    
    // If all queries execute successfully
    connection.commit();
} catch (SQLException e) {
    // Rollback entire transaction if any query fails
    connection.rollback();
}
/* Transaction End */

Explanation:

  • Disable auto-commit mode.
  • Execute multiple SQL queries.
  • If all queries succeed → commit() saves changes.
  • If any query fails → rollback() restores the database to its previous state.

🔹 Real-Life Example

       Bank Transfer Scenario:
  • SQL Query 1 → Deduct amount from Account A
  • SQL Query 2 → Add amount to Account B
  • If both succeed → Commit transaction
  • If any fails → Rollback entire transfer to prevent data inconsistency

Comments

Popular posts from this blog

History of Java Programming Language | Features, Origin & Uses

Inheritance in Java: Types, Examples, and Explanation

Java Programming Features Every Beginner Should Know