Transaction strategy: understand transaction traps — forward

Common errors to pay attention to when implementing transactions in the Java platform

Transactions are often used in applications to maintain a high degree of data integrity and consistency. If you don't care about the quality of the data, you don't have to use transactions. After all, transaction support in the Java platform will reduce performance, cause locking problems and database concurrency problems, and increase the complexity of applications.

But developers who don't care about business get into trouble. Almost all business-related applications require a high degree of data quality. The financial investment industry wasted tens of billions of dollars on failed transactions, Bad data is the second major factor leading to this result (see). Although the lack of transaction support is only one factor leading to bad data (but it is the main factor), it can be considered that billions of dollars are wasted in the financial investment industry due to the lack of transaction support or insufficient transaction support.

Ignoring transaction support is another cause of the problem. I often hear statements like "we don't need transaction support in our applications because these applications never fail". Yes, I know some applications that rarely or never throw exceptions. These applications are based on well written code, well written verification routines, fully tested, and supported by code coverage, which can avoid performance loss and transaction related complexity. This type of application only needs to consider one feature of transaction support: atomicity. Atomicity ensures that all updates are treated as a single unit, either committed or rolled back. However, rollback or simultaneous updates are not the only aspect of transaction support. On the other hand, isolation will ensure that one unit of work is independent of other units of work. Without proper transaction isolation, other units of work can access updates made by an active unit of work, even if the unit of work has not completed. In this way, business decisions will be made based on some data, which will lead to failed transactions or other negative (or expensive) results.

Therefore, considering the high cost and negative impact of bad data, And the importance of business (and necessity) for these basic common sense, you need to use transaction processing and learn how to deal with possible problems. Many problems often occur after you add transaction support to your application. Transactions do not always work as expected in the Java platform. This article will explore the reasons for this. I will use code examples to introduce some of the problems I continue to see in this field And experienced common transaction traps, mostly in production environments.

Although most of the code examples in this article use the spring framework (version 2.5), the transaction concept is the same as that in the EJB 3.0 specification_ cnnew1@TransactionAttribute Replace the spring framework @ transactional annotation with the annotation. If the two frameworks use different concepts and technologies, I will give both spring framework and EJB 3.0 source code examples.

It's best to start with the simplest scenario, that is, using local transactions, commonly known as database transactions. In the early days of database persistence (such as JDBC), we generally delegated transactions to the database. After all, this is what the database should do. Local transactions are well suited for a logical unit of work (LUW) that performs a single insert, update, or delete statement. For example, consider the simple JDBC code in Listing 1, which inserts a stock trading order into the trade table:

public long insertTrade(TradeData Trade) throws Exception { Connection dbConnection = ds.getConnection(); try { Statement sql = dbConnection.createStatement(); String stmt = "INSERT INTO TradE (ACCT_ID,SIDE,SYMBOL,SHARES,PRICE,STATE)" "VALUES (" Trade.getAcct() + "','" Trade.getAction() + "','" Trade.getSymbol() + "'," Trade.getShares() + "," Trade. getPrice() + ",'" Trade. getState() + "')"; sql. executeUpdate(stmt,Statement.RETURN_GENERATED_KEYS); ResultSet rs = sql. getGeneratedKeys(); if (rs.next()) { return rs.getBigDecimal(1).longValue(); } else { throw new Exception("Trade Order Insert Failed"); } } finally { if (dbConnection != null) dbConnection.close(); } } } The JDBC code in Listing 1 does not contain any transaction logic, it just saves the transaction orders in the trade table in the database. In this case, the database handles transaction logic. In LUW, this is a good single database maintenance operation. But what if you need to update the account balance while inserting the transaction order into the database? As shown in Listing 2:
In this case, the inserttrade () and updateacct () methods use standard JDBC code without transactions. After the inserttrade() method ends, the database saves (and submits) the transaction order. If the updateacct() method fails for any reason, the transaction order will still be saved in the trade table at the end of the placetrade() method, which will lead to inconsistent data in the database. If the placetrade () method uses transactions, both activities will be included in one LUW. If the account update fails, the transaction order will be rolled back. With the continuous popularity of Java persistence framework, such as hibernate TopLink and Java persistence API (JPA), we seldom write simple JDBC code again. More often, we use updated object relational mapping (ORM) framework to reduce the work, that is, to replace all the troublesome JDBC code with a few simple method calls. For example, to insert the transaction order of the JDBC code example in, using the spring framework with JPA, you can map the tradedata object to the trade table and replace all the JDBC code with the JPA code in Listing 3: public long inserttrade (TradeData trade) throws Exception {
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>