Must Know :
Transaction Management in JDBC :
Here are the most important points about Transaction Management in JDBC.
- A transaction means, it is a group of operations used to perform a task.
- A transaction can reach either success state or failure state.
- If all operations are completed successfully then the transaction becomes success.
- If any one of the operation fail then all remaining operations will be cancelled and finally transaction will reach to fail state.
Types of Transactions :
The basic transactions are of two types.
- Local Transactions
- Global / Distributed Transactions
Local Transactions :
If all the operations are executed on one/same database, then it is called as local transaction.
Global / Distributed Transaction :
If the operations are executed on more than one database then it is called as global transactions.
Example : If we transfer the money from account1 to account2 of same bank, then it is called as local transaction. If we transfer the money from account1 to account2 of different banks, then it is called as global or distributed transaction.
Transaction Management in JDBC Example :
We can get the Transaction support in JDBC from Connection interface. The Connection interface given 3 methods to perform Transaction Management in JDBC.
- setAutoCommit()
- commit()
- rollback()
Transaction setAutoCommit() :
Before going to begin the operations, first we need to disable the auto commit mode. This can be done by calling setAutoCommit(false).
By default, all operations done from the java program are going to execute permanently in database. Once the permanent execution happened in database, we can’t revert back them (Transaction Management is not possible).
Transaction commit() :
If all operations are executed successfully, then we commit a transaction manually by calling the commit() method.
Transaction rollback() :
If any one of the operation failed, then we cancel the transaction by calling rollback() method.
Complete Example :
Output:
If we update with the statements,
We can get the Exception like below and the transaction will be roll backed.
No comments:
Post a Comment