Java's JDBC Simple transaction processing

Source: Internet
Author: User

1. What is a Java transaction

It is generally assumed that transactions are related to databases. a transaction is a sequence of operations that accesses a database, and the database application system accesses the database through a transaction set. The proper execution of a transaction causes the database to transition from one state to another state.

Transactions must be subject to the ACID principles established by ISO/IEC. Acid is an abbreviated transaction of atomicity (atomicity), consistency (consistency), isolation (isolation), and persistence (durability) that must be subject to the acid principle established by ISO/IEC. Acid is an abbreviation for atomicity (atomicity), consistency (consistency), isolation (isolation), and persistence (durability).

A, atomic nature

that is, the transaction is either fully executed or not executed at all. If all the child transactions of a transaction are committed successfully, all database operations are committed, the database state is transformed, and if there is a child transaction failure, the database operations of the other child transactions are rolled back, that is, the database returns to the state before the transaction execution, and no state transitions occur.

B, consistency

the execution of a transaction causes the database to transition from a correct state to another correct state.

C, the isolation of

before a transaction is properly committed, it is not allowed to make any changes to the data to any other transaction, that is, before the transaction is committed correctly, its possible results should not be displayed to any other transaction.

D, persistence

after the transaction is committed correctly, the result is persisted in the database, and the transaction results are saved even if there are other failures after the transaction commits.

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, if it operates a database, is implemented through JDBC. The addition, modification, and deletion are implemented indirectly by the corresponding method, and the control of the transaction is transferred to the Java program code accordingly. Therefore, the transactions of database operations are customarily referred to as Java transactions.

2. Why business is required

A simple sentence: keep your data consistent.

3. Java transaction type

There are three types of Java transactions: JDBC Transaction, JTA (Java Transaction API) transaction, container transaction. Here are the simplest introduction, and finally will introduce the use of JDBC transaction, the other two people can search their own under the study.

A, 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.

B, JTA (Java Transaction API) Transactions

JTA is a high-level, unrelated, protocol-agnostic API that enables applications and application servers to access transactions using JTA. 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 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. Xaconnections is a JDBC connection that participates in JTA transactions, you will need to set up Xadatasource with the application server's administration tools. 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 are not the same as 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, applications should use Usertransaction.begin (), Usertransaction.commit (), and Sertransaction.rollback ().

C, container transactions

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 implementation. Relative coding implements JTA transaction management, and 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.

d. Use of JDBC Transactions(1) Steps:

    first, set the transaction to be submitted as non-auto-commit:Conn.setautocommit (false);Next, put the code that needs to add the transaction into the Try,catch block. then, the commit operation of the transaction is added inside the try block, indicating that the operation has no exception and commits the transaction:conn.commit ();in particular, do not forget to add a ROLLBACK transaction within the CATCH block, indicating an exception to the operation and revoking the transaction:Conn.rollback ();Finally, set the transaction submission method to Auto-commit:Conn.setautocommit (true);so, with a few simple steps, we can finish writing the transaction.

(2) Pseudo-code:

Con = drivermanager.getconnection (Url, user, password);string result =  ""; string sql1 =  "";// last_insert_id ()   Get the Automatically incrementing idstring sql2 =  "" that was just inserted; Int flag;try {    con.setautocommit (false);//  Change the default submission method for JDBC transactions      pstmt = con.preparestatement (SQL1);    flag =  Pstmt.executeupdate ();    if  (flag > 0)  {         pstmt = con.preparestatement (SQL2);         int i = pstmt.executeupdate ();         if   (i > 0)  {             Con.commit ();//submit JDBC Transaction             result =   "add data success!!";         } else {             result =  "add data fail!!";        }    } else {         result =  "add data fail!!";     }} catch  (sqlexception e)  {    try {         con.rollback ();//rollback JDBC Transaction     } catch   (SQLEXCEPTION E1)  {    // TODO Auto-generated catch  block        result =  "add data fail!!  sqlexception ";         e1.printstacktrace ();     }    result =  "add data fail!!  sqlexception ";    &Nbsp;e.printstacktrace ();}  finally {    try {         Con.setautocommit (True); //  The default submission method for recovering JDBC Transactions     } catch  (SQLException  e)  {    // TODO Auto-generated catch block         e.printstacktrace ();    }}return result;



4. Three different transactions

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.

5. 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's JDBC Simple transaction processing

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.