What is transaction java

What Is Transaction Management in Java?

Join the DZone community and get the full member experience.

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.

Читайте также:  Python zen на русском

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.

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.

Читайте также:  text-transform

After it is aborted, there are two options:

Restarting the transaction is only possible if there are no internal logical errors.

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.

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().

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.

Читайте также:  Парсинг xml python beautifulsoup

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(); >>> 

Transaction committed Successfully.

Opinions expressed by DZone contributors are their own.

Источник

The Java EE 5 Tutorial

To emulate a business transaction, a program may need to perform several steps. A financial program, for example, might transfer funds from a checking account to a savings account using the steps listed in the following pseudocode:

begin transaction debit checking account credit savings account update history log commit transaction

Either all three of these steps must complete, or none of them at all. Otherwise, data integrity is lost. Because the steps within a transaction are a unified whole, a transaction is often defined as an indivisible unit of work.

A transaction can end in two ways: with a commit or with a rollback. When a transaction commits, the data modifications made by its statements are saved. If a statement within a transaction fails, the transaction rolls back, undoing the effects of all statements in the transaction. In the pseudocode, for example, if a disk drive were to crash during the credit step, the transaction would roll back and undo the data modifications made by the debit statement. Although the transaction fails, data integrity would be intact because the accounts still balance.

In the preceding pseudocode, the begin and commit statements mark the boundaries of the transaction. When designing an enterprise bean, you determine how the boundaries are set by specifying either container-managed or bean-managed transactions.

Copyright © 2010, Oracle and/or its affiliates. All rights reserved. Legal Notices

Источник

Оцените статью