Summary and difference of JDBC transaction and JTA Distributed transaction in Java _java

Source: Internet
Author: User
Tags rollback stmt jboss

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

JDBC Transaction

All the actions of JDBC include transactions based on a connection, and in JDBC, transaction management through connection objects. In JDBC, the common and transaction-related methods are: Setautocommit, commit, rollback, etc.

Let's look at a simple JDBC transaction code:

 public void Jdbctransfer () {Java.sql.Connection conn = null; 
     try{conn = conn =drivermanager.getconnection ("Jdbc:oracle:thin: @host: 1521:sid", "username", "userpwd"); 
 
     Set Autocommit to False//If set to True the database will identify each data update as a transaction and automatically submit Conn.setautocommit (FALSE);  
     stmt = Conn.createstatement (); 
     Reduce the amount in account A to Stmt.execute ("\ Update t_account Set amount = amount-500 where account_id = ' a '"); 
 
     Increase the amount in the B account to Stmt.execute ("\ Update t_account Set amount = Amount + where account_id = ' B '"); 
     Submit transaction Conn.commit (); 
       Transaction commit: The two-step operation of the transfer also succeeded in the catch (SQLException Sqle) {try{///abnormal, rollback in this transaction do Conn.rollback ();  
       Transaction rollback: The two-step operation of the transfer completely revokes the Stmt.close ();  
     Conn.close ();  
   }catch (Exception ignore) {} sqle.printstacktrace (); }  
} 

The code above implements a simple transfer function that controls the transfer operation through transactions, either committed or rolled back.

Advantages and disadvantages of JDBC transactions

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

However, the JDBC transaction has one limitation: a JDBC transaction cannot span multiple databases!!! So, if you are involved in multiple database operations or distributed scenarios, JDBC transactions are powerless.

JTA Affairs

Why need JTA

In general, JDBC transactions can solve the problem of data consistency, and since his usage is relatively simple, many people know nothing about Java transactions but the JDBC transaction, or someone knows the transactions in the framework (such as Hibernate, Spring), and so on. However, because JDBC is unable to implement distributed transactions, and today more and more distributed scenarios, the JTA transaction arises.

If you don't have a situation in your job that you can't solve with JDBC, you can only say that the project you're doing is too small. Take the electricity merchant website, we generally divide an electric dealer website horizontally to divide into the commodity module, the Order module, the shopping cart module, the message module, the payment module and so on. Then we deploy different modules to different machines, and each module communicates through a remote service call (RPC). Provide services externally to a distributed system.

A payment process is to interact with multiple modules, each of which is deployed in different machines, and each module operates a database that is inconsistent, and JDBC cannot be 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 add the Pointservice.update () to the fund accounts 
  ;//Call the integration service to add points 
  to the integral account Accountingservice.insert (); Invoke the accounting service to write the accounting original voucher 
  merchantnotifyservice.notify () to the accounting system;//Call Merchant Notification Service to send payment result notification to merchant 
 

The above code is a simple payment process operation, which calls five services, all five services are called through RPC, how to use JDBC to ensure transactional consistency? I added a @transactional annotation to the method, but because the distributed service was invoked, the transaction did not achieve the acid effect.

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. Components of any of the following Java platforms can participate in a JTA transaction: JDBC Connection, JDO PersistenceManager object, JMS queue, JMS theme, Enterprise JavaBeans (EJB), one with Java EE Connector Architecture The resource allocator compiled by the specification.

Definition of JTA

The Java Transaction API (Java Transaction API, referred to as JTA) is a Java Enterprise version of the application interface that allows distributed transactions across multiple XA resources to be completed in the Java environment.

JTA and its fellow Java transaction services (Jts;java Transactionservice) provide distributed transaction services for the Java EE platform. However, JTA only provides an interface, does not provide a specific implementation, but by the Java server provider based on the JTS specification, common JTA implementations have the following:

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

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

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

    • Begin: Open a transaction
    • Commit: Commit the current transaction
    • Rollback: Rolling back current transaction
    • Setrollbackonly: Mark current transaction as rollback
    • Settransactiontimeout: Sets the event of the transaction beyond this event, throws an exception, rolls back the transaction

Here, it is worth noting that, instead of using usertransaction, you can convert ordinary JDBC operations directly into JTA operations, JTA is required for DataSource, connection, and resource, only in accordance with the XA specification, And the classes that implement the relevant interfaces of the XA specification can participate in the JTA transaction, and for the XA specification, see my other article for an introduction. Here, to make a remark, the current mainstream database supports the XA specification.

To use a JTA transaction, you need to have 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 JTA transactions. A Xadatasource object is the factory of a Xaconnection object. Xaconnection is a JDBC connection that participates in JTA transactions.

To use a JTA transaction, you must use Xadatasource to produce a database connection that produces 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.

Sample code:

public void Jtatransfer () {javax.transaction.UserTransaction tx = null; 
     Java.sql.Connection conn = null; try{tx = (javax.transaction.UserTransaction) context.lookup ("java:comp/usertransaction");//Obtain a JTA transaction, in this case by the JBoss container Management Javax.sql.DataSource ds = (javax.sql.DataSource) context.lookup ("Java:/xaoracleds"); 
      To obtain a database connection pool, you must have a database that supports XA, driver tx.begin (); 
 
       conn = Ds.getconnection (); 
 
       Set Autocommit to False//If set to True the database will identify each data update as a transaction and automatically submit Conn.setautocommit (FALSE);  
       stmt = Conn.createstatement (); 
       Reduce the amount in account A to Stmt.execute ("\ Update t_account Set amount = amount-500 where account_id = ' a '");  Add the amount in the B account to Stmt.execute ("\ Update t_account Set amount = Amount + where account_id = 
 
       ' B ' "); 
       Submit transaction Tx.commit (); Transaction commit: Two-step operation of transfer simultaneous success} catch (SQLException Sqle) {try{///Unexpected exception, rollback in this transaction TX.ROllback ();  
         Transaction rollback: The two-step operation of the transfer completely revokes the Stmt.close ();  
       Conn.close ();  
     }catch (Exception ignore) {} sqle.printstacktrace (); 
 }  
   }

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

Standard distributed Transactions

A distributed transaction (distributed Transaction) includes a transaction manager (Transaction Manager) and one or more resource managers (Resource manager). A Resource Manager (Resource Manager) is a persistent data store of any type. The transaction manager (transaction manager) assumes responsibility for the communication of all transaction participants.

Look at the description of the distributed transaction above does it compare with the transaction management in 2PC? , 2PC is actually an implementation of the XA-compliant transaction manager that coordinates multiple resource managers. I've had several articles about 2PC and 3PC before, these articles describe how the transaction manager in a distributed transaction coordinates the unified commit or rollback of multiple transactions, and I have a few more articles detailing the distributed transaction-related content, including but not limited to global transactions, DTP models, flexible transactions, etc.

Advantages and disadvantages of JTA

The advantage of JTA is that it provides a solution for distributed transactions, strict acid. However, the standard JTA approach to transaction management is not commonly used in day-to-day 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.
The JTA itself is a cumbersome API.
Typically JTA can only be used in an application server environment, so using JTA can limit the reusability of the code.

Summarize

There are three types of Java transactions: JDBC Transactions, JTA (Java Transaction API) transactions, container transactions, where JDBC's transactional usage is simpler and is suitable for handling the same data source operations. JTA transactions are relatively complex and can be used to handle transactions across multiple databases and are a solution to distributed transactions.

Here also to say briefly, although the JTA transaction is Java provides a set of APIs that can be used in distributed transactions, but the implementation of different EE platform is not the same, and are not very convenient to use, so generally in the project is not too much use of this more responsible API. Now the industry more commonly used distributed transaction solutions are mainly asynchronous message to ensure that the type, TCC, the maximum effort to inform.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.