Java Transaction Management

Source: Internet
Author: User

First, what is a Java transaction

The general idea is that transactions are only relevant to the database.

Transactions must be subject to the ACID principles established by ISO/IEC. Acid is an abbreviation for atomicity (atomicity), consistency (consistency), isolation (isolation), and persistence (durability). The atomicity of a transaction indicates that any failure during the execution of the transaction will invalidate any modifications made by the firm. Consistency means that when a transaction fails, all data that is affected by the transaction should be restored to the state it was before the http://www.xiaoyaolife.com service was executed. Isolation represents the modification of data during the execution of a transaction and is not visible to other transactions before the transaction commits. Persistence indicates that the submitted data should be in the correct state when the transaction execution fails.

In layman's knowledge, a transaction is a set of atomic operating units, which, from a database perspective, is a set of SQL instructions, or all of them succeed, and if one of the instructions executes with an error for one reason, all previously executed instructions are revoked. The simpler answer is: either all succeeds or the revocation is not executed.

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

In fact, a Java application system, if you want to manipulate the database, is written through JDBC. Additions, modifications, and deletions are written indirectly by corresponding methods, and the control of transactions is transferred to the Java program code accordingly. Therefore, the transactions of database operations are customarily referred to as Java transactions.

Second, why the need for business

Transactions are made to address data security operations, and transaction control is essentially a secure access to control data. With a simple example: for example, bank transfer business, account A to the account of the 1000 yuan to the B account, a balance of the first account to subtract 1000 yuan, then the B account to increase 1000 yuan. If there is a problem in the intermediary network, a account minus 1000 yuan has ended, b because the network outage and operation failed, then the entire business failure, must be control, require a account transfer business revocation. This can guarantee the correctness of the business, the completion of this operation will require a transaction, the A-account capital reduction and the B-account funds to a transaction inside, or all of the successful execution, or the operation is all revoked, so that the security of the data.

Iii. Types of Java transactions

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

1. JDBC Transaction

The JDBC transaction is controlled with the Connection object. The JDBC Connection Interface (java.sql.Connection) provides two transaction modes: Autocommit and Manual commit. Java.sql.Connection provides the following methods of controlling transactions:

public void Setautocommit (Boolean)
public boolean getautocommit ()
public void commit ()
public void rollback ()

When using JDBC transaction demarcation, you can combine multiple SQL statements into a single transaction. One drawback of JDBC transactions is that the scope of a transaction is limited to a single database connection. A JDBC transaction cannot span multiple databases.

Using JDBC in JavaBean for transactional processing
How do you combine multiple SQL statements into a single transaction in JDBC? In JDBC, when you open a Connection object connection, the default is Auto-commit mode, and each SQL statement is treated as a transaction, that is, each time a statement is executed, it is automatically acknowledged by the transaction. In order to be able to combine multiple SQL statements into a single transaction, the Auto-commit mode is masked out. If the commit () method is not called after the Auto-commit mode is masked, the SQL statement will not receive a transaction acknowledgment. All SQL after the last commit () method call is confirmed when the method commit () is called.

public int Delete (int sID) {
DBC = new DatabaseConnection ();
Connection con = dbc.getconnection ();
try {
Con.setautocommit (false);//Change the default submission mode for JDBC transactions
Dbc.executeupdate ("Delete from bylaw where id=" + SID);
Dbc.executeupdate ("Delete from bylaw _content where id=" + SID);
Dbc.executeupdate ("Delete from bylaw _affix where bylawid=" + SID);
Con.commit ();//Submit JDBC Transaction
Con.setautocommit (TRUE);//Restore the default submission mode for JDBC transactions
Dbc.close ();
return 1;
}
catch (Exception exc) {
Con.rollback ();//rollback JDBC Transaction
Exc.printstacktrace ();
Dbc.close ();
return-1;
}
}
2. JTA (Java Transaction API) transaction

JTA is a high-level, unrelated, protocol-agnostic API that applications and application servers can use JTA to access transactions.

JTA allows applications to perform distributed transactions-access and update data on two or more network computer resources, which can be distributed across multiple databases. The JTA support of the JDBC driver greatly enhances the data access capability.

If you plan to define transactions with JTA, you need to have a JDBC driver that writes Javax.sql.XADataSource, Javax.sql.XAConnection, and Javax.sql.XAResource interfaces. A driver that writes these interfaces will be able to participate in the JTA transaction. A Xadatasource object is a factory of a Xaconnection object. Xaconnection S is a JDBC connection that participates in JTA transactions.

You will need to set up Xadatasource with the Application Server's administration tool. The relevant guidance can be learned from the application server and the JDBC driver documentation.

The Java EE application queries the data source with JNDI. Once the application finds the data source object, it calls Javax.sql.DataSource.getConnection () to get a connection to the database.

XA connections differ from non-XA connections. Be sure to remember that the XA connection participates in the JTA transaction. This means that the XA connection does not support the auto-commit feature of JDBC. Also, the application must not call Java.sql.Connection.commit () or Java.sql.Connection.rollback () on the XA connection. Instead, the application should use Usertransaction.begin (), Usertransaction.commit (), and Sertransaction.rollback ().

JTA is the Java EE Solution for transactional services. Essentially, it is part of the Java EE model that describes a transactional interface, such as a usertransaction interface, that the developer uses directly or through the Java EE container to ensure that the business logic can run reliably. The JTA has three main interfaces, namely the UserTransaction interface, the TransactionManager interface, and the Transaction interface. These interfaces share common transactional operations, such as commit () and rollback (), but also contain special transactional operations such as suspend (), resume () and enlist (), which appear only on specific interfaces to allow a certain degree of access control in writing. For example, UserTransaction can perform transaction partitioning and basic transactional operations, while TransactionManager can perform context management.

An application can call the Usertransaction.begin () method to start a transaction that is associated with the current line threads in which the application is running. The underlying transaction manager actually handles the association between the thread and the transaction. The Usertransaction.commit () method terminates the transaction associated with the current thread. The Usertransaction.rollback () method discards the current transaction associated with the current thread.

public int Delete (int sID) {
DatabaseConnection DBC = null;
DBC = new DatabaseConnection ();
Dbc.getconnecti On ();
UserTransaction transaction = Sessioncontext.getusertransaction ();//Get JTA Transaction
try {
Transaction.begin ();  Start JTA transaction
dbc.executeupdate ("Delete from bylaw where id=" + SID);
Dbc.executeupdate ("Delete from bylaw _content where id=" + SID);
Dbc.executeupdate ("Delete from bylaw _affix where bylawid=" + SID);  
Transaction.commit ();//Submit JTA Transaction
Dbc.close ();
return 1;
}
catch (Exception exc) {
try {
Transaction.rollback ();//JTA transaction rollback
}
catch (Exception ex) { //JTA transaction rollback error handling
Ex.printstacktrace ();
}
Exc.printstacktrace ();
Dbc.close ();
Return-1;
}
}
 3, container transaction

Container transactions are mainly provided by the Java EE Application Server, and the container transactions are mostly based on JTA, which is a jndi-based, fairly complex API to write. Writing JTA transaction management with relative coding, we can accomplish the same function through the container transaction management mechanism (CMT) provided by the EJB container, which is provided by the Java EE Application Server. This allows us to simply specify which method to join the transaction, and once specified, the container will be responsible for the transaction management task. This is our way of doing civil work, because in this way we can exclude the transaction code from the logic code, and all the difficulties to the Java EE container to solve. Another benefit of using EJB CMT is that programmers do not have to care about the coding of the JTA API, but in theory we have to use EJBS.

Four or three different transaction differences

1. The limitations of JDBC transaction control are within a database connection, but they are simple to use.

2. JTA transactions are powerful, and transactions can span multiple databases or multiple DAO, and are more complex to use.

3, container transaction, mainly refers to the Java EE Application Server provides transaction management, limited to the use of EJB applications.


V. Summary

Transaction control is an indispensable part of building the Java EE application, and it is very important for the whole application to choose what kind of transaction to apply. In general, the JDBC transaction can be selected in the case of a single JDBC connection connection, with the option to use JTA transactions across multiple connections or databases, and if EJB is used, consider using EJB container transactions.

Java Transaction Management

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.