Java Transaction--JTA principle __jta

Source: Internet
Author: User
Tags rollback stmt

The previous article introduced JDBC transactions, which can handle the transactions of a single data source to meet the needs of most transactions, but JDBC transactions do not solve multiple data sources and distributed transaction problems, and the Java platform provides us with solutions--jta. This article will explore some of the details of JTA.

A distributed transaction
Transactions within a database, such as operations on multiple tables, are typically treated as local transactions. The transaction objects of the database and JDBC are local transactions, while the objects of the distributed transactions are global transactions.
A global transaction is a distributed transaction processing environment in which multiple databases may need to work together to accomplish a global transaction, for example, several different databases may be updated in a transaction. Operations on the database occur throughout the system, but must be committed or rolled back. At this point, a database commits itself not only to the success of its own operations, but also to the success of the operations of other databases related to global transactions, and if any operation of any database fails, all operations of all databases participating in this transaction must be rolled back.
In general, a database cannot know what other databases are doing, so in a DTP environment, transaction middleware is required to notify and coordinate the submission or rollback of related databases. A database only alludes its own operations (recoverable) to a global transaction, which is a distributed transaction processing model.
Two XA specifications
The X/open organization, now Open group, defines a distributed transaction processing model. The X/open DTP Model (1994) includes application (AP), transaction manager (TM), Resource Manager (RM), Communication Resource Manager (CRM) four parts.
A common transaction manager (TM) is a transaction middleware, such as JDBC or hibernate-provided transactionmanager, a common resource manager (RM) is a database, typically a data source, such as JDBC or a third-party-provided datasource. The common Communication Resource Manager (CRM) is message middleware, such as JMS.
The typical DTP model is as follows:

Three JTA Realization
We are also mentioned in the previous paper transfer as an example to illustrate the specific implementation of JTA.

	<span style= "FONT-SIZE:18PX;" 
		 > public void Transferaccount () {usertransaction usertx = null; 
		 Connection Conna = null; 
				
		 Statement Stmta = null; 
		 Connection CONNB = null; 
    
		 Statement STMTB = null; try{//Get Transaction Management Object USERTX = (usertransaction) getcontext (). Lookup ("\ Java:comp/usertransac 
			 tion "); 
			
			 Get the database connection from database A Conna = Getdatasourcea (). getconnection (); 
      
                        Get the database connection from database B CONNB = Getdatasourceb (). getconnection ();
			
			 Start transaction usertx.begin (); 
			 Reduce the amount in account A to Stmta = Conna.createstatement ();
			
			 Stmta.execute ("update t_account set amount = amount-500 where account_id = ' A '"); 
			 Increase the amount in the B account to STMTB = Connb.createstatement ();
			
			 Stmtb.execute ("\ Update t_account Set amount = Amount + where account_id = ' B '");
			 Submit transaction Usertx.commit (); Transaction submission: The two-step operation of the transfer succeeds simultaneously (database A and data in database B are both updated)} CAtch (SQLException sqle) {try{///Unexpected exception, rollback in this transaction usertx.rollback (); 
                 Transaction rollback: Two-step operation of transfer complete revocation//(database A and data update in database B are simultaneously revoked) stmt.close (); 
				 Conn.close (); ... 
			 } 
			
		 catch (Exception ignore) {} sqle.printstacktrace (); 
		 catch (Exception ne) {e.printstacktrace (); }}</span>

Note: In the example above, we used two databases, that is, Conna and CONNB are connections from different databases.
Four JTA Realization principle
JTA is the way to implement the transaction manager. To understand JTA's implementation, you first need to understand its architecture: it includes both the transaction manager (Transaction Manager) and one or more resource managers (Resource Manager) that support the XA protocol, and we can think of the resource manager as any type of persisted data The transaction manager is responsible for the coordination and control of all the transaction participation units. Depending on the object being targeted, we can interpret the JTA transaction manager and resource manager as two aspects: the developer-oriented interface (transaction manager) and the service provider-oriented implementation interfaces (resource manager). The main part of the development interface is the UserTransaction object referenced in the above example, where the developer implements the distributed transaction in the information system through this interface, while the implementation interface is used to standardize the transaction services provided by the provider (such as the database connection provider), and it agrees with the resource management function of the transaction. Enables JTA to perform collaborative communication between heterogeneous transaction resources. In the case of databases, IBM provides a database driver for distributed transactions, Oracle also provides a database driver for distributed transactions, and when using both DB2 and Oracle two database connections, JTA That is, you can implement distributed transactions based on the agreed interface coordinator and two transaction resources. It is the different implementations based on the unified specification that enable JTA to coordinate and control the transaction resources of different databases or JMS vendors, as shown in the following illustration:

Developers use the developer interface to implement application support for global transactions; each provider (database, JMS, etc.) provides transaction resource management functions according to the specification of provider interface; transaction manager (TransactionManager The use of distributed transactions is mapped to the actual transaction resources and coordinated and controlled between transaction resources. Below, this article describes the three main interfaces, including UserTransaction, Transaction, and TransactionManager, and the methods that they define.
Developer-oriented interfaces are usertransaction (as shown in the previous example), and developers typically use this interface only to implement JTA transaction management, which defines the following methods:
Begin ()-Start a distributed transaction
Commit ()-Commit a transaction
Rollback ()-ROLLBACK TRANSACTION
GetStatus ()-Returns the status of the distributed transaction associated with the current thread
Setrollbackonly ()-Identifies the distributed transaction that is associated with the current thread to be rolled back
Provider-oriented implementation interface mainly involves TransactionManager and Transaction two objects

The

        transaction represents a physical transaction when the developer calls the Usertransaction.begin () method TransactionManager Creates a Transaction transaction object that marks the beginning of the transaction and associates the object through Threadlocale to the current thread. Methods such as commit (), rollback (), GetStatus () in the UserTransaction interface are ultimately delegated to the corresponding method of the Transaction class for execution.

Registersynchronization (synchronization Sync)-callback interface, Hibernate, and other ORM tools have their own transaction control mechanisms to guarantee transactions, But they also need a callback mechanism to be notified when the transaction completes, triggering some processing work, such as clearing the cache. This involves the Transaction callback interface registersynchronization.         The tool can inject a callback program into a transaction through this interface, and the callback program will be activated when the transaction is successfully committed. TransactionManager itself does not assume the actual transaction processing function, it is more to act as a bridge between the user interface and the implementation interface. The following is a list of the methods defined in TransactionManager, and you can see that most of the transaction methods in this interface are the same as usertransaction and Transaction. When the developer calls the Usertransaction.begin () method, TransactionManager creates a Transaction transaction object (which marks the beginning of the transaction) and associates the object through Threadlocale to the current thread ; the same usertransaction.commit () invokes Transactionmanager.commit (), which takes the transaction object Transaction from under the current thread and commits the transaction represented by this object, called Transaction.commit ()
The following will introduce the JTA implementation principle to the reader through specific code. The following figure lists the Java classes involved in the example implementation where USERTRANSACTIONIMPL implements the UserTransaction interface, Transactionmanagerimpl implements the TransactionManager interface, Transactionimpl implements the Transaction interface
The JTA implementation class diagram is as follows:




Why do you have to support a distributed transaction from a database connection that is obtained from a data source that supports transactions? In fact, the data source supporting the transaction is different from the normal data source, and it implements the additional Xadatasource interface. We can simply interpret xadatasource as a normal data source (inherited java.sql.PooledConnection), but it adds Getxaresource methods to support distributed transactions. In addition, the database connection returned by Xadatasource is different from the normal connection, and this connection implements the Xaconnection interface in addition to all the features defined by Java.sql.Connection. We can interpret xaconnection as a common database connection that supports database operations for all JDBC specifications, except that xaconnection adds support for distributed transactions. The following class diagram allows readers to understand the relationship between these interfaces:




The database connection that an application obtains from a data source that supports distributed transactions is the implementation of the Xaconnection interface, and the session created by this database connection (Statement) adds functionality to support distributed transactions, as shown in the following code:
JTA Transaction Resource Processing

<span style= "FONT-SIZE:18PX;" >public void Transferaccount () { 
			
		 usertransaction usertx = null; 
				
		 Connection conn = null; 
		 Statement stmt = null; 
    
		 try{ 
		        //Get Transaction Management Object
			 Usertx = (usertransaction) getcontext (). Lookup ("
			 java:comp/usertransaction") ; 
Gets the database connection from the database, GETDATASOURCEB returns the data source that supports the distributed transaction
			 conn = Getdatasourceb (). getconnection (); 
                        Session stmt has been enhanced to support distributed transactions
			 stmt = Conn.createstatement (); 
			
                        Start Transaction
			 Usertx.begin ();
             Stmt.execute ("Update t_account ... where account_id = ' A '"); 
			 Usertx.commit ();
} catch (SQLException Sqle) { 
			 //Handle exception code
		 } catch (Exception ne) { 
			 e.printstacktrace (); 
		 } 
	 } </span>
Five summary

JTA's implementation is actually derived from JDBC transactions, JTA is different from JDBC: The resource manager needs to implement the Xadatasource interface, as long as the implementation of this interface can be implemented through the JTA transaction manager.

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.