JDBC Transaction Management in Java with Example

Here you will learn to implement JDBC transaction management in java.

By default database is in auto commit mode. That means for any insert, update or delete operation the changes takes place immediately in database.

What is Transaction?

Transaction involves several sql queries that are considered as one unit. For example money transfer done in bank is a kind of transaction as it involves two steps. First debit the x amount of money from source account and then credit that amount to destination account.

Why Transaction Management Required?

To avoid data inconsistency transaction management is required. Lets understand this by one example. Money transferring involves two steps, suppose money is debited from source account but failed to credit to destination account. This arises data inconsistency.

Now this problem can be solved using transaction management. If any of the operation is failed in transaction then all the operations are rolled back and the database restored back to the state where the transaction was started.

JDBC Transaction Management in Java with Example

Image Source

JDBC Transaction Management Example

In JDBC we can begin the transaction by disabling auto commit using setAutoCommit(false) method and end the transaction by commit() method. Roll back can be done using rollback() method.

In case of any exception the rollback should be done in catch block. If due to some reason sql statements or queries are not executed properly then rollback should be done before commit.

Take below example, here I am transferring money from one account to another. Transaction will take place only when both debit and credit money operations will be performed successfully otherwise rollback will be done.


Commit Successful!

Comment below if you have any queries related to above jdbc transaction management example.

Leave a Comment

Your email address will not be published. Required fields are marked *