DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Java Virtual Threads and Scaling
  • Java’s Next Act: Native Speed for a Cloud-Native World

Trending

  • A Complete Guide to Modern AI Developer Tools
  • How the Go Runtime Preempts Goroutines for Efficient Concurrency
  • A Guide to Developing Large Language Models Part 1: Pretraining
  • Transforming AI-Driven Data Analytics with DeepSeek: A New Era of Intelligent Insights
  1. DZone
  2. Coding
  3. Java
  4. What Is Transaction Management in Java?

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.

By 
Mahesh Sharma user avatar
Mahesh Sharma
·
Oct. 10, 22 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
13.2K Views

Join the DZone community and get the full member experience.

Join For Free

In 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: 
    1. Many types of failures, including hardware issues and system crashes.
    2. 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


Java 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.

  1. Terminate: Terminate the transaction.
  2. Committed: After successful completion, committed.

The top three roles in transaction management are listed below. As follows:

  1. 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.
  2. 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.
  3. 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.

Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Java Virtual Threads and Scaling
  • Java’s Next Act: Native Speed for a Cloud-Native World

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!