Transaction--JDBC transactions and JTA transactions in Java

Source: Internet
Author: User
Tags rollback stmt jboss

This article describes the Java EE and transaction-related content, before reading this article, I hope the reader has a certain understanding of the distribution.

There are three types of Java transactions: JDBC Transaction, JTA (Java Transaction API) transaction, container transaction. Common container transactions such as spring transactions, container transactions are mainly provided by the Java EE Application Server, the container transaction is mostly based on JTA completion, which is a jndi-based, rather complex API implementation. Therefore, this article does not discuss container transactions at this stage. This paper mainly introduces two basic transactions in the development of Java EE: JDBC transaction and JTA transaction.

JDBC Transaction

The JDBC transaction, which is used in Java to control database transactions. All JDBC behavior includes transactions that are based on a connection, which is managed by the connection object in JDBC. In JDBC, common transaction-related methods are: Setautocommit, commit, rollback, and so on.

The transaction of JDBC is relatively simple, mainly through the JDBC API to control the database transaction execution.

Let's look at a simple JDBC transaction code:

public void Jdbctransfer () {Java.sql.Connection conn = null; try{conn = conn =drivermanager.getconnection ("Jdbc:oracle:t Hin: @host: 1521:sid "," username "," userpwd "); Set auto-commit to FALSE,//If set to True the database will identify each data update as a transaction and automatically commit Conn.setautocommit (false); stmt = Conn.createstatement (); Reduce the amount in account a by up to Stmt.execute ("update t_account set amount = amount-500 where account_id = ' a '"); Increase the amount in the B account by up to Stmt.execute ("update t_account Set amount = Amount + where account_id = ' B '"); Commit Transaction Conn.commit (); Transaction commit: The two-step operation of the transfer succeeds at the same time} catch (SQLException Sqle) {try{//exception occurred, rollback in this transaction to do Conn.rollback ();//Transaction rollback: Two-step transfer operation completely revoke Stmt.close () ; Conn.close (); }catch (Exception ignore) {} sqle.printstacktrace (); } }

The code above implements a simple transfer function that controls the transfer of transactions, either commits or rolls back.

Advantages and disadvantages of JDBC transactions

JDBC provides the most basic support for transactional operations of databases using Java. With JDBC transactions, we can put multiple SQL statements into the same transaction, guaranteeing their acid properties. The main advantage of the JDBC transaction is that the API is relatively simple and can achieve the most basic transactional operations, and the performance is relatively good.

However, the JDBC transaction has one limitation: a JDBC transaction cannot span multiple databases!!! So, if it involves multiple database operations or distributed scenarios, the JDBC transaction is powerless.

JTA Transactions

Why do I need JTA

In general, JDBC transactions can solve problems such as data consistency, and since he is relatively simple to use, many people know only that there is a JDBC transaction in the Java transaction, or that someone knows the transactions in the framework (such as Hibernate, Spring), and so on. However, because JDBC cannot implement distributed transactions, and today there are more and more distributed scenarios, JTA transactions emerge.

If you don't have a scenario where the JDBC transaction can't be solved at work, you can only say that the projects you're doing are still too small. Take the e-commerce website, we generally put an e-commerce website horizontally split into commodity modules, order module, shopping cart module, message module, payment module. Then we deploy different modules to different machines, and the modules communicate through remote service invocation (RPC). Provide services externally to a distributed system.

A payment process interacts with multiple modules, each of which is deployed in different machines, and each module operates with inconsistent databases, and JDBC is not used to manage transactions. Let's look at a piece of code:

/ Payment Order Processing /@Transactional (rollbackfor = exception.class) public void CompleteOrder () {orderdao.update ();// Order Service local Update order status accountservice.update (); Call the Fund Account Service to fund account plus pointservice.update (); Call Points service to add points Accountingservice.insert () to points account; Call the accounting service to the accounting system to write the accounting source document Merchantnotifyservice.notify (); Call Merchant Notification Service to send payment result notification to merchant}

The above code is an operation of a simple payment process in which five services are invoked, and the five services are called by RPC, how can I use JDBC to ensure transactional consistency? I added the @transactional annotation to the method, but because of the call to the distributed service, the transaction did not achieve acid effect. (for the issue of distributed consistency, refer to: A study of distributed consistency)

JTA transactions are more powerful than JDBC transactions. A JTA transaction can have multiple participants, while a JDBC transaction is limited to a single database connection. The components of any of the following Java platforms can participate in a JTA transaction: JDBC Connection, JDO PersistenceManager object, JMS queue, JMS topic, Enterprise JavaBeans (EJB), one with Java EE Connector The resource allocator for Architecture specification compilation.

Definition of JTA

The Java Transaction API (Java Transaction API, or JTA) is a Java Enterprise Edition application interface that allows distributed transactions spanning multiple XA resources to be completed in a Java environment.

JTA and its fellow Java transaction services (Jts;java Transactionservice) provide distributed transaction services for the EE platform. However, JTA only provides an interface and does not provide a specific implementation, but is provided by the Java EE server provider according to the JTS specification, the common JTA implementations are as follows:

JTA implementations provided by the 1.J2EE container (JBoss)

2. Independent JTA implementations: such as Jotm,atomikos. These implementations can be used in environments that do not use the Java EE Application Server to provide distributed transaction assurance. such as Tomcat,jetty and common Java applications.

JTA inside provides java.transaction.UserTransaction, which defines the following methods

Begin: Open a transaction

Commit: Commit the current transaction

Rollback: Rolling back the current transaction

Setrollbackonly: Mark the current transaction as rollback

Settransactiontimeout: Sets the transaction event, exceeds this event, throws an exception, rolls back the transaction

Here, it is worth noting that the normal JDBC operation can be transferred directly to the JTA operation without using UserTransaction, JTA is required for DataSource, connection and resource, only in accordance with the XA specification, and implement the XA specification of the relevant interface class to participate in the JTA transaction, about the XA specification, see my other article is related to the introduction. Here, in a word, the current mainstream database supports the XA specification.

To use JTA 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 will be able to participate in the JTA transaction. A Xadatasource object is a factory of a Xaconnection object. Xaconnection is a JDBC connection that participates in JTA transactions.

To use JTA transactions, you must use Xadatasource to generate a database connection, resulting in a connection that is an XA connection.

The difference between XA connections (javax.sql.XAConnection) and non-XA (java.sql.Connection) connections is that XA can participate in JTA transactions and does not support autocommit.

public void Jtatransfer () {javax.transaction.UserTransaction tx = NULL; Java.sql.Connection conn = null; try{tx = (ja vax.transaction.UserTransaction) context.lookup ("Java:comp/usertransaction"); Get JTA transaction, in this case javax.sql.DataSource ds = (javax.sql.DataSource) context.lookup ("Java:/xaoracleds") managed by the JBoss container; To obtain the database connection pool, there must be an XA-enabled database, driver Tx.begin (); conn = Ds.getconnection (); Set auto-commit to FALSE,//If set to True the database will identify each data update as a transaction and automatically commit Conn.setautocommit (false); stmt = Conn.createstatement (); Reduce the amount in account a by up to Stmt.execute ("update t_account set amount = amount-500 where account_id = ' a '"); Increase the amount in the B account by up to Stmt.execute ("update t_account Set amount = Amount + where account_id = ' B '"); Commit Transaction Tx.commit (); Transaction commit: The two-step operation of the transfer succeeds at the same time} catch (SQLException Sqle) {try{//exception occurred, rollback in this transaction to do Tx.rollback ();//Transaction rollback: Two-step operation of the transfer is completely revoked stmt.close (); c Onn.close (); }catch (Exception ignore) {} sqle.printstacktrace (); } }

The above example is a transfer operation that uses JTA transactions, which are relatively dependent on the Java EE container and need to get usertransaction and connection through Jndi.

Standard distributed Transactions

A distributed transaction (distributed Transaction) consists of a transaction manager (Transaction Manager) and one or more resource managers (Resource manager). A Resource Manager (Resource Manager) is any type of persisted data store. The transaction manager (transaction Manager) undertakes the responsibility of communicating with each other in the unit of the transaction.

JTA implementation is also based on these distributed transaction participants implementation, specific details about the implementation of JTA is not the focus of this article, interested students can read the "JTA Deep Adventures-Principles and implementation"

See the above about distributed transactions is not the same as the transaction management in the 2PC compared?

, 2PC is actually a way of implementing an XA compliant transaction manager that coordinates multiple resource managers.

I have a few articles about 2PC and 3PC, that several articles about how the transaction manager in the distributed transaction to coordinate the unified commit or rollback of multiple transactions, I will also have a few articles in detail about the distributed transaction related content, including but not limited to global transactions, DTP model, flexible transactions.

Advantages and disadvantages of JTA

The advantage of JTA is that it provides a solution for distributed transactions with strict acid. However, the standard JTA approach to transaction management is not commonly used in daily development because he has many drawbacks:

Achieve complex

Typically, JTA usertransaction need to be fetched from Jndi. This means that if we use JTA, we need to use both JTA and Jndi.

JTA itself is a cumbersome API.

Typically JTA can only be used in an application server environment, so using JTA limits the reusability of code.

Summarize

There are three types of Java transactions: JDBC Transaction, JTA (Java Transaction API) transaction, container transaction, and JDBC transaction operation usage is relatively simple, suitable for handling the same data source operation. JTA transactions are relatively complex and can be used to handle transactions across multiple databases, which is a solution for distributed transactions.

Let's just say that although the JTA transaction is a set of APIs that Java provides for distributed transactions, the implementations of different EE platforms are not the same, and are not very easy to use, so the more responsible API is generally not used in the project. Now the industry more commonly used distributed transaction solutions are mainly asynchronous message assurance type, TCC, the maximum effort notification, and so on.

Transaction--JDBC transactions and JTA transactions in Java

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.