Java transactions: Principles and Applications of Java transactions

Source: Internet
Author: User

Java transactions: Principles and Applications of Java transactions

1. What is a JAVA transaction?

Generally, transactions are only related to databases.

Transactions must follow the ACID principles established by ISO/IEC. ACID is short for atomicity, consistency, isolation, and durability. The atomicity of a transaction indicates that any failure during the transaction execution will invalidate any modification made by the transaction. Consistency indicates that when the transaction fails, all data affected by the transaction should be restored to the status before the transaction is executed. Isolation indicates the modification of data during transaction execution, which is invisible to other transactions before the transaction is committed. Persistence indicates that the data status should be correct when the transaction fails.

In a general sense, a transaction is a group of atomic operation units. From the database perspective, it is a group of SQL commands, or all of them are successfully executed. If one of the commands is incorrect for some reason, undo All commands previously executed. To put it simply, either the execution is successful or the execution is canceled.

Since the concept of transactions comes from the database, what is a Java transaction? What is the relationship between them?

In fact, a Java application system uses JDBC to operate databases. Adding, modifying, and deleting are implemented indirectly through corresponding methods, and transaction control is also transferred to Java program code. Therefore, the transaction habits of database operations are called Java transactions.

Ii. Why Java transactions?

Transactions are proposed to solve data security operations. In fact, transaction control controls secure data access. For example, in the bank transfer business, account A must transfer the RMB 1000 from his account to account B. The balance of account A must first be reduced by RMB 1000, then, Account B needs to add 1000 yuan. If A problem occurs in the intermediate network, the operation of account A minus 1000 yuan has ended, and account B fails due to network interruption, the entire business fails and must be controlled, requiring account A to cancel the transfer business. This ensures the correctness of the business. To complete this operation, A transaction is required to reduce the funds of account A and increase the funds of Account B to A transaction. Either all the operations are successfully executed or all the operations are revoked, this ensures data security.

Iii. Java transaction types

There are three types of Java transactions: JDBC transactions, JTA (Java Transaction API) transactions, and container transactions.

1. JDBC transactions

JDBC transactions are controlled by Connection objects. The JDBC Connection interface (java. SQL. Connection) provides two transaction modes: Automatic commit and manual commit. Java. SQL. Connection provides the following methods to control transactions:

Public void setAutoCommit (boolean)
Public boolean getAutoCommit ()
Public void commit ()
Public void rollback ()


When you use the JDBC transaction interface, you can combine multiple SQL statements into one transaction. One disadvantage of JDBC transactions is that the transaction scope is limited to a database connection. A jdbc transaction cannot span multiple databases.

2. JTA (Java Transaction API) Transaction

JTA is a high-level implementation-independent and protocol-independent API. Applications and application servers can use JTA to access transactions.

JTA allows applications to execute Distributed Transaction Processing-data is accessed and updated on two or more network computer resources, which can be distributed across multiple databases. The JTA support of the JDBC driver greatly enhances data access capabilities.

If you plan to use JTA to define transactions, you need a JDBC driver that implements the javax. SQL. XADataSource, javax. SQL. XAConnection, and javax. SQL. XAResource interfaces. A driver that implements these interfaces can participate in JTA transactions. A XADataSource object is the factory of A XAConnection object. XAConnection s is the JDBC connection that participates in the JTA transaction.

You will need to use the administration tool of the application server to set XADataSource. You can learn the relevant instructions from the documents of the application server and the JDBC driver.

J2EE applications use JNDI to query data sources. Once the application finds the data source object, it calls javax. SQL. DataSource. getConnection () to obtain the connection to the database.

XA connections are different from non-XA connections. Make sure that the XA connection is involved in the JTA transaction. This means that the XA connection does not support the JDBC automatic submission function. At the same time, applications must not call java. SQL. Connection. commit () or java. SQL. Connection. rollback () for XA connections ().

On the contrary, the application should use UserTransaction. begin (), UserTransaction. commit (), and serTransaction. rollback ().

3. Container transactions

Container transactions are mainly provided by the J2EE application server, and most container transactions are completed based on JTA. This is a very complicated API implementation based on JNDI. To implement JTA transaction management through relative encoding, we can use the container Transaction Management Mechanism (CMT) provided by the EJB container to complete the same function, which is provided by the J2EE application server. This allows us to simply specify which method to add to the event. Once specified, the container will be responsible for the transaction management task. This is our civil solution, because in this way, we can exclude the transaction code from the logic code, and at the same time hand over all the difficulties to the J2EE server for solving. Another advantage of using ejb cmt is that programmers do not need to care about the jta api encoding. However, in theory, we must use EJB.

Iv. Differences between three Java transactions

1. Restrictions of JDBC transaction control are in a database connection, but they are easy to use.

2. JTA transactions have powerful functions. transactions can span multiple databases or multiple DAO transactions, which are also complicated to use.

3. Container transactions mainly refer to the transaction management provided by the J2EE application server, which is limited to the use of EJB applications.

V. Summary

Java transaction control is an indispensable part of J2EE application construction. It is vital for the entire application system to reasonably select the transaction to be applied. In general, you can select JDBC transactions when connecting a single JDBC connection. When connecting multiple connections or databases, you need to use JTA transactions. If EJB is used, you can consider using EJB container transactions.

Java JDBC transaction details

Features of transactions:

1) atomicity: a transaction is the logical unit of work of the database and must be an atomic unit of work. Modifications to the data are either performed in full or not all.

2) consistency: when the transaction is completed, all data must be consistent. In related databases, all rules must be applied to transaction modifications to maintain the integrity of all data.

3) isolation: the execution of a transaction cannot be affected by other transactions.

4) durability: Once a transaction is committed, its operations are permanently stored in the database. Even if you perform the rollback operation again, you cannot cancel the changes.

Transaction: a unit of concurrency control and a sequence of user-defined operations. These operations are either done or not done. They are an inseparable unit of work. Through transactions, SQL server can bind a set of logical operations to ensure data integrity on the server. Transactions generally start with begin transaction and end with commit or rollback. Commint indicates commit, that is, all operations to commit a transaction. Specifically, all data updates in the transaction are written back to the physical database on the disk, and the transaction ends normally. Rollback indicates Rollback, that is, when a transaction encounters a fault and the transaction cannot continue, the system revokes all completed operations on the database in the transaction, roll back to the starting state of the transaction.

Automatic transaction commit: each separate statement is a transaction. Each statement implies a commit. (Default)

Explicit transaction: starts with the display of begin transaction and ends with commit or rollback.

Implicit Transaction: when the connection is operated in implicit transaction mode, the SQL server database engine instance automatically starts a new transaction after committing or rolling back the current transaction. You do not need to describe the beginning of a transaction. You only need to commit or roll back each transaction. However, each transaction still ends explicitly with commit or rollback. When the connection sets the implicit transaction mode to open, an implicit transaction is automatically started when the database engine instance executes any of the following statements for the first time: alter table, insert, create, open, delete, revoke, drop, select, fetch, truncate table, grant, and update are valid until a commit or rollback statement is issued. After the first transaction is committed or rolled back, the database engine instance automatically starts a new transaction when the connection executes any of the preceding statements. This instance will continuously generate a hidden transaction chain until the hidden transaction mode is closed.

 

Java JDBC transaction mechanism

First, let's take a look at the major problems that the existing JDBC operations will cause. For example, there is a business: When we modify a piece of information, we can query it again. This is a simple business, it is also very easy to implement, but when this service is deployed on a multi-threaded and high-concurrency platform, the problem naturally arises. For example, after we execute a modification, before executing the query, a thread also executes the modification statement. This is where we execute the query again. The information we see may be different from what we modified. To solve this problem, we must introduce the JDBC transaction mechanism. In fact, the code implementation is very simple. Here is an example of the implementation principle for your reference:

Private Connection conn = null;

Private PreparedStatement ps = null;

Try {

Conn. setAutoCommit (false); // set automatic submission to false

Ps.exe cuteUpdate ("Modify SQL"); // perform the Modification Operation

Ps.exe cuteQuery ("query SQL"); // execute the query operation

Conn. commit (); // manually submit after two operations are successful

} Catch (Exception e ){

Conn. rollback (); // if one of the operations fails, both operations fail.

E. printStackTrace ();

}

Transaction-related theory

1. The four attributes of Transaction (ACID)

Atomicity (Atomic) modifies data either in full or not in full.

Consistent maintains the consistency of the data status before and after the transaction is executed.

The processing of one transaction cannot affect the processing of another transaction.

The Durable transaction processing ends, and its effect is persistent in the database.


2. Problems Caused by concurrent Transaction Processing

A dirty read (dirty read) Transaction reads data that has not been committed by another transaction,

Non-repeatable read: the operation of one transaction causes another transaction to read different data twice.

Phantom read: the operations of one transaction lead to different results of the two queries before and after the other transaction.

Example:

When transactions A and B are concurrently executed,

After transaction A is updated, transaction B's select statement reads uncommitted data from transaction A. At this time, transaction A rollback will invalidate the data read by transaction B.

After the select statement of transaction B reads data, the update operation of transaction A changes the data selected by transaction B. At this time, transaction B reads the data again and finds that the data is different twice before and after.

After the select statement of transaction B reads data, transaction A inserts or deletes A record that meets the select condition of transaction A. At this time, transaction B selects again, the previous non-existent reCord ("phantom") is found, or a previous record is missing.

 

JDBC transaction support

JDBC supports transactions in three aspects:

1. Auto-commit mode)

Connection provides an auto-commit attribute to specify when the transaction ends.

A. When auto-commit is true, when each independent SQL operation is completed, the transaction is automatically committed immediately, that is, each SQL operation is a transaction.

When is an independent SQL statement executed? The JDBC specification specifies:

For data operation languages (DML, such as insert, update, delete) and data definition languages (such as create and drop), once the statement is executed, it is deemed that the execution is complete.

When the ResultSet object associated with the select statement is closed, the execution is deemed to have completed.

When all the ResultSet objects associated with the stored procedure or other statements that return multiple results are closed, all update count (number of rows affected by the update, delete, and other statement operations) and output parameter (the output parameter of the stored procedure) are obtained, and the execution is complete.

B. When auto-commit is set to false, each transaction must call the commit Method for submission or call the rollback method for rollback. The default value of auto-commit is true.

JDBC provides five different transaction isolation levels, which are defined in Connection.

 

2. Transaction Isolation level (Transaction Isolation Levels)

JDBC defines five transaction isolation levels:

TRANSACTION_NONE JDBC driver does not support transactions

TRANSACTION_READ_UNCOMMITTED allows dirty reads, non-repeated reads, and Phantom reads.

TRANSACTION_READ_COMMITTED: dirty reads are prohibited, but repeated and Phantom reads are not allowed.

TRANSACTION_REPEATABLE_READ prevents dirty reads and repeated reads.

TRANSACTION_SERIALIZABLE: Disable dirty reads, non-repeated reads, and Phantom reads.

 

3. SavePoint)

JDBC defines the SavePoint interface and provides a more fine-grained transaction control mechanism. After a save point is set, you can roll back to the State at the save point, rather than rolling back the entire transaction.

The setSavepoint and releaseSavepoint methods of the Connection interface can be used to set and release the storage point.

Although the JDBC Specification defines the above supported behaviors of transactions, database vendors may have different levels of support for transactions for each JDBC driver. If any settings are made in the program, the desired effect may not be obtained. Therefore, JDBC provides the DatabaseMetaData interface and a series of methods for obtaining JDBC features. For example, the DatabaseMetaData. supportsTransactionIsolationLevel method can be used to determine the support for the transaction isolation level, and the DatabaseMetaData. supportsSavepoints method can be used to determine the support for the storage point.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.