Home > Java > JavaBase > Transaction processing in JAVA

Transaction processing in JAVA

Release: 2020-06-16 16:12:39
forward
3607 people have browsed it

Transaction processing in JAVA

1. What is a Java transaction?

The usual concept is that transactions are related to the database. A transaction is a sequence of operations to access the database. The database application system completes access to the database through transaction sets. The correct execution of transactions causes the database to transition from one state to another.

Transactions must comply with the ACID principles established by ISO/IEC.

ACID is the abbreviation for atomicity, consistency, isolation and durability. Transactions must comply with the ACID principles established by ISO/IEC. ACID is the abbreviation for atomicity, consistency, isolation and durability.

a. Atomicity

means indivisibility. Either all transactions are executed or none are executed. If all sub-transactions of the transaction are submitted successfully, all database operations are submitted and the database state is converted; if any sub-transaction fails, the database operations of other sub-transactions are rolled back, that is, the database returns to the state before the transaction was executed. No state transition occurs.

b. Consistency

The execution of a transaction converts the database from one correct state to another correct state.

c, Isolation

Before the transaction is correctly committed, any changes to the data by the transaction are not allowed to be provided to any other transaction, that is, before the transaction is correctly committed, its possible results are not Should be shown to any other transaction.

d. Durability

After a transaction is submitted correctly, its results will be permanently stored in the database. Even if there are other failures after the transaction is submitted, the processing results of the transaction will be saved.

Since the concept of transaction comes from the database, what is a Java transaction? What's the connection?

In fact, if a Java application system operates a database, it is implemented through JDBC. Then addition, modification, and deletion are all implemented indirectly through corresponding methods, and the control of transactions is also transferred to the Java program code accordingly. Therefore, database operation transactions are customarily called Java transactions.

2. Why transactions are needed

A simple sentence: maintain data consistency.

3. Java transaction types

There are three types of Java transactions: JDBC transactions, JTA (Java Transaction API) transactions, and container transactions. Here is the simplest introduction. Finally, we will introduce the use of jdbc transactions. You can search and learn the other two types by yourself.

a. JDBC transactions

JDBC transactions are controlled using Connection objects. The JDBC Connection interface (java.sql.Connection) provides two transaction modes: automatic submission and manual submission. java.sql.Connection provides the following methods to control transactions:

 public void setAutoCommit(boolean)
 public boolean getAutoCommit()
 public void commit()
 public void rollback()
Copy after login

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

b. JTA (Java Transaction API) transaction

JTA is a high-level, implementation-independent, and protocol-independent API. 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 JDBC driver's JTA support greatly enhances data access capabilities.

If you plan to use JTA to define transactions, you will 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 JTA transactions. A XADataSource object is a factory for XAConnection objects. XAConnections are JDBC connections that participate in JTA transactions, and you will need to set up the XADataSource using the application server's administration tools.

J2EE applications use JNDI to query data sources. Once the application finds the data source object, it calls javax.sql.DataSource.getConnection() to obtain a connection to the database.

XA connections are different from non-XA connections. It is important to remember that XA connections participate in JTA transactions. This means that XA connections do not support JDBC's autocommit feature. At the same time, applications must not call java.sql.Connection.commit() or java.sql.Connection.rollback() on XA connections.

Instead, applications should use UserTransaction.begin(), UserTransaction.commit(), and serTransaction.rollback().​

c. Container transactions

Container transactions are mainly provided by the J2EE application server. Most container transactions are completed based on JTA. This is a fairly complex API implementation based on JNDI. Compared with coding to implement JTA transaction management, we can complete the same function through the container transaction management mechanism (CMT) provided by the EJB container. This function is provided by the J2EE application server.

This allows us to simply specify which method to add to the transaction. Once specified, the container will be responsible for transaction management tasks. This is our civil engineering solution, because in this way we can exclude transaction code from logical coding, and at the same time leave all difficulties to the J2EE container to solve.

使用EJB CMT的另外一个好处就是程序员无需关心JTA API的编码,不过,理论上我们必须使用EJB。

d、JDBC事务的使用

(1)步骤:

首先,设置事务的提交方式为非自动提交:conn.setAutoCommit(false);接下来,将需要添加事务的代码放入try,catch块中。

然后,在try块内添加事务的提交操作,表示操作无异常,提交事务:conn.commit();尤其不要忘记,在catch块内添加回滚事务,表示操作出现异常,撤销事务:conn.rollback();最后,设置事务提交方式为自动提交:conn.setAutoCommit(true);这样,通过简单的几步,我们就可以完成对事务处理的编写了。

(2)伪代码:

con = DriverManager.getConnection(url, user, password);
String result = "";
String sql1 = "";
// LAST_INSERT_ID() 获取刚刚插入的自动递增的ID
String sql2 = "";
int flag;
try {
    con.setAutoCommit(false);// 更改JDBC事务的默认提交方式
    pstmt = con.prepareStatement(sql1);
    flag = pstmt.executeUpdate();
    if (flag > 0) {
        pstmt = con.prepareStatement(sql2);
        int i = pstmt.executeUpdate();
        if (i > 0) {
            con.commit();//提交JDBC事务
            result = "add data success!!";
        } else {
            result = "add data fail!!";
       }
    } else {
        result = "add data fail!!";
    }
} catch (SQLException e) {
    try {
        con.rollback();//回滚JDBC事务
    } catch (SQLException e1) {
    // TODO Auto-generated catch block
        result = "add data fail!! SQLException";
        e1.printStackTrace();
    }
    result = "add data fail!! SQLException";
    e.printStackTrace();
} finally {
    try {
        con.setAutoCommit(true); // 恢复JDBC事务的默认提交方式
    } catch (SQLException e) {
    // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
return result;
Copy after login

4、三种事务差异

1、JDBC事务控制的局限性在一个数据库连接内,但是其使用简单。

2、JTA事务的功能强大,事务可以跨越多个数据库或多个DAO,使用也比较复杂。

3、容器事务,主要指的是J2EE应用服务器提供的事务管理,局限于EJB应用使用。

5、总结

事务控制是构建J2EE应用不可缺少的一部分,合理选择应用何种事务对整个应用系统来说至关重要。一般说来,在单个JDBC 连接连接的情况下可以选择JDBC事务,在跨多个连接或者数据库情况下,需要选择使用JTA事务,如果用到了EJB,则可以考虑使用EJB容器事务。

更多相关知识请关注java基础教程栏目

The above is the detailed content of Transaction processing in JAVA. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:oschina.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template