What Is Transaction Management in Java?
We will discuss transaction management in Java; we should know what a transaction is; therefore, the following are some important points about the transaction.
Join the DZone community and get the full member experience.
Join For FreeIn this tutorial, we will discuss transaction management in Java using examples. But before moving to transaction management, we should know what a transaction is. Therefore, the following are some important points about transactions for better understanding:
- A transaction is a segment of program execution that accesses and can alter different pieces of data.
- A consistent database must be visible to a transaction.
- The database can briefly be unavailable during transaction execution inconsistent.
- The database is updated after the transaction is successfully completed (committed) and has to remain constant.
- A transaction's modifications to the database are finalized when it commits.
- Multiple transactions may run concurrently.
- There are two key challenges to address:
- Many types of failures, including hardware issues and system crashes.
- Execution of many transactions occurs simultaneously.
Types of Transactions
Every SQL query will be regarded as a transaction in JDBC. A database connection created with JDBC will operate in auto-commit mode (auto-commit value is TRUE). The SQL statement will automatically be committed upon execution.
Occasionally, we might wish to commit the transaction after a few more SQL statements have been executed. The auto-commit variable has to be changed to False at that point. It prevents data from being committed before all queries have been run. If a transactional exception occurs, we may roll back () modifications and restore the original state. Using the ACID characteristics, transaction management can be described properly.
ACID Properties
A transaction is a segment of program execution that accesses and may alter different pieces of data. The database system must ensure the following in order to protect data integrity:
Atomicity: Either all of the transaction's operations are correctly represented in the database, or none of them is. The transaction management component keeps it up to date.
Consistency: The consistency of the database is maintained when a transaction is carried out in isolation. It falls under the purview of the application programmer.
Isolation: A transaction must be oblivious of any other transactions that are running simultaneously, even though numerous transactions may execute simultaneously. Other concurrently conducted transactions must not see the outcomes of intermediate transactions. To put it another way, for each pair of transactions Ti and Tj, Ti perceives that either Tj completed execution before Ti began or Tj began execution after Ti was completed. The concurrency control manager controls it.
Durability: When a transaction goes through successfully, the modifications made even when there are system problems and updates to the database continue. It is your duty to do so as a rehabilitation coordinator.
Example:
Transaction to transfer $50 from account A to account B:
1.read(A)
2. A:= A – 20
3.write(A)
4.read(B)
5. B := B + 20
6.write(B)
Requirement for Atomicity – If the transaction fails after step three, but before step six, the system must make sure that the database has not been updated. As a result, there will be an inconsistency.
Requirement for Consistency – The condition for consistency is that when the transaction is completed, the total of A and B remains unaltered.
Requirement for Isolation – If another transaction is permitted to access the partially modified database between steps three and six, it will encounter an inconsistent database (the total of A and B will be lower than it should be). By processing transactions serially, or one after another, isolation may be quickly assured.
Requirement for Durability – The database alterations made by the transaction must endure failures until the user has been informed that the transaction has finished (i.e., the $20 has been transferred).
Transaction State
Active: Active is the starting state; it is maintained while the transaction is being executed.
Partially Committed: After the last statement has been completed, the transaction is partially committed.
Failed: following the realization that regular execution is no longer possible.
Aborted: the transaction is rolled back, and the database is returned to how it was before the transaction was started.
After it is aborted, there are two options:
Restarting the transaction is only possible if there are no internal logical errors.
- Terminate: Terminate the transaction.
- Committed: After successful completion, committed.
The top three roles in transaction management are listed below. As follows:
- Commit: We want to make the changes in the Database permanent once the SQL statements have been executed. Calling the commit () function is necessary. Commit often refers to making permanent changes to the database. The modifications cannot be reversed or revoked. However, we have the ability to modify database data.
- Rollback: Rollback reverses all modifications up to the most recent commit or specified savepoint. We could occasionally desire to reverse the modifications. For instance, in a single nested query, one portion has been properly run while the other has produced an error. If an exception has happened at that point and we wish to reverse the modifications made by the first section, we should utilize the Rollback() function.
- Savepoint: A savepoint enables the creation of checkpoints in a transaction and enables rolling back to a specific savepoint. Once a transaction is committed or rolled back, all savepoints that were made for it are instantly deleted and rendered useless.
Transaction Management Techniques
Five techniques for managing transactions are offered by the connection interface. They are:
1. setAutoCommit() Method
The AutoCommit setting is set to TRUE by default. The SQL statement will automatically be committed upon execution. We may set the value to AutoCommit by utilizing the setAutoCommit() function.
2. Commit() Method
The data is committed using the commit method. The commit is the term used after the SQL query has been executed (). The modifications made by the SQL statement will be committed.
Syntax:
con.commit();
3. Rollback() Method
Until the last commit, the modifications can be undone using the rollback procedure. When the SQL statements are being executed, if there is a problem or an exception. The transaction can be rollback().
Syntax:
con.rollback();
4. setSavepoint() Method
You have more control over the transaction, thanks to Savepoint. You may use the rollback() function to undo any changes made up to or after the savepoint when you establish a savepoint in a transaction (a collection of SQL statements) (). A new savepoint may be made using the setSavepoint() function.
5. releaseSavepoint() Method
The generated savepoint is removed using it.
Program:
import java.io.*;
import java.util.*;
import java.sql.*;
class TransactionManagement
{
public static void main(String[] args) throws Exception {
Connection connection = null;
Statement statement = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/user", "root","123456");
connection.setAutoCommit(false);
statement = connection.createStatement();
statement.executeUpdate("insert person values ('1','USA','JACK')")
connection.commit();
System.out.println("Transaction committed Successfully.");
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
connection.rollback();
}}}
Output:
Transaction committed Successfully.
Opinions expressed by DZone contributors are their own.
Comments