In the previous article of this series, we talked about the basic issues of Java transaction processing and the Service layer and DAO layer. In this article, we will take BankService as an example to learn a case of transaction processing failure.
Download the github source code in the following ways:
Git clone https://github.com/davenkin/java_transaction_workshop.git
The function of BankService is as follows: a user has two accounts: a bank account and an insurance account, with their respective account numbers, the transfer method of BankService transfers funds from the user's bank account to the insurance account. The two DAO methods are used to access the two account tables respectively.
Define a BankService interface as follows:
package davenkin;public interface BankService { public void transfer(int fromId, int toId, int amount);}
In the two DAO objects, we obtain the Connection through the same DataSource passed in, And then operate the database directly through the APIS provided by JDBC.
The DAO class that defines the operation of the bank account table is as follows:
package davenkin.step1_failure;import javax.sql.DataSource;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;public class FailureBankDao { private DataSource dataSource; public FailureBankDao(DataSource dataSource) { this.dataSource = dataSource; } public void withdraw(int bankId, int amount) throws SQLException { Connection connection = dataSource.getConnection(); PreparedStatement selectStatement = connection.prepareStatement("SELECT BANK_AMOUNT FROM BANK_ACCOUNT WHERE BANK_ID = ?"); selectStatement.setInt(1, bankId); ResultSet resultSet = selectStatement.executeQuery(); resultSet.next(); int previousAmount = resultSet.getInt(1); resultSet.close(); selectStatement.close(); int newAmount = previousAmount - amount; PreparedStatement updateStatement = connection.prepareStatement("UPDATE BANK_ACCOUNT SET BANK_AMOUNT = ? WHERE BANK_ID = ?"); updateStatement.setInt(1, newAmount); updateStatement.setInt(2, bankId); updateStatement.execute(); updateStatement.close(); connection.close(); }}
FailureBankDao's withdraw method extracts the amount of amount from the user account whose account is bankId in the bank account table (BANK_ACCOUNT.
In the same way, the DAO class of the insurance account is defined as follows:
package davenkin.step1_failure;import javax.sql.DataSource;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;public class FailureInsuranceDao { private DataSource dataSource; public FailureInsuranceDao(DataSource dataSource){ this.dataSource = dataSource; } public void deposit(int insuranceId, int amount) throws SQLException { Connection connection = dataSource.getConnection(); PreparedStatement selectStatement = connection.prepareStatement("SELECT INSURANCE_AMOUNT FROM INSURANCE_ACCOUNT WHERE INSURANCE_ID = ?"); selectStatement.setInt(1, insuranceId); ResultSet resultSet = selectStatement.executeQuery(); resultSet.next(); int previousAmount = resultSet.getInt(1); resultSet.close(); selectStatement.close(); int newAmount = previousAmount + amount; PreparedStatement updateStatement = connection.prepareStatement("UPDATE INSURANCE_ACCOUNT SET INSURANCE_AMOUNT = ? WHERE INSURANCE_ID = ?"); updateStatement.setInt(1, newAmount); updateStatement.setInt(2, insuranceId); updateStatement.execute(); updateStatement.close(); connection.close(); }}
The deposit method of the FailureInsuranceDao class stores the amount of amount to the insurance account table (INSURANCE_ACCOUNT). In this way, in BankService, we can call the withdraw method of FailureBankDao to obtain a certain amount of deposits, then, call the deposit method of FailureInsuranceDao to save the deposit to the insurance account table. Everything seems OK. The implementation of the BankService interface is as follows:
package davenkin.step1_failure;import davenkin.BankService;import javax.sql.DataSource;import java.sql.Connection;import java.sql.SQLException;public class FailureBankService implements BankService{ private FailureBankDao failureBankDao; private FailureInsuranceDao failureInsuranceDao; private DataSource dataSource; public FailureBankService(DataSource dataSource) { this.dataSource = dataSource; } public void transfer(int fromId, int toId, int amount) { Connection connection = null; try { connection = dataSource.getConnection(); connection.setAutoCommit(false); failureBankDao.withdraw(fromId, amount); failureInsuranceDao.deposit(toId, amount); connection.commit(); } catch (Exception e) { try { assert connection != null; connection.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } finally { try { assert connection != null; connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } public void setFailureBankDao(FailureBankDao failureBankDao) { this.failureBankDao = failureBankDao; } public void setFailureInsuranceDao(FailureInsuranceDao failureInsuranceDao) { this.failureInsuranceDao = failureInsuranceDao; }}
In the transfer method of FailureBankService, we first obtain the Connection through DataSource, and then call connection. setAutoCommit (false) the manual submission mode has been enabled. If everything goes well, commit. If an exception occurs, rollback. Next, let's test our BankService.
To prepare the test data, we define a BankFixture class, which is responsible for preparing the test data before each test and saving 1111 yuan to the bank account (2222) and insurance account (1000) respectively. BankFixture also provides two helper methods (getBankAmount and getInsuranceAmount) to help us retrieve data from the database for data verification. We use the in-memory mode of the HSQL database to facilitate testing without starting the database server. The BankFixture class is defined as follows:
package davenkin;import org.junit.Before;import javax.sql.DataSource;import java.sql.*;public class BankFixture{ protected final DataSource dataSource = DataSourceFactory.createDataSource(); @Before public void setUp() throws SQLException { Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement(); statement.execute("DROP TABLE BANK_ACCOUNT IF EXISTS"); statement.execute("DROP TABLE INSURANCE_ACCOUNT IF EXISTS"); statement.execute("CREATE TABLE BANK_ACCOUNT (\n" + "BANK_ID INT,\n" + "BANK_AMOUNT INT,\n" + "PRIMARY KEY(BANK_ID)\n" + ");"); statement.execute("CREATE TABLE INSURANCE_ACCOUNT (\n" + "INSURANCE_ID INT,\n" + "INSURANCE_AMOUNT INT,\n" + "PRIMARY KEY(INSURANCE_ID)\n" + ");"); statement.execute("INSERT INTO BANK_ACCOUNT VALUES (1111, 1000);"); statement.execute("INSERT INTO INSURANCE_ACCOUNT VALUES (2222, 1000);"); statement.close(); connection.close(); } protected int getBankAmount(int bankId) throws SQLException { Connection connection = dataSource.getConnection(); PreparedStatement selectStatement = connection.prepareStatement("SELECT BANK_AMOUNT FROM BANK_ACCOUNT WHERE BANK_ID = ?"); selectStatement.setInt(1, bankId); ResultSet resultSet = selectStatement.executeQuery(); resultSet.next(); int amount = resultSet.getInt(1); resultSet.close(); selectStatement.close(); connection.close(); return amount; } protected int getInsuranceAmount(int insuranceId) throws SQLException { Connection connection = dataSource.getConnection(); PreparedStatement selectStatement = connection.prepareStatement("SELECT INSURANCE_AMOUNT FROM INSURANCE_ACCOUNT WHERE INSURANCE_ID = ?"); selectStatement.setInt(1, insuranceId); ResultSet resultSet = selectStatement.executeQuery(); resultSet.next(); int amount = resultSet.getInt(1); resultSet.close(); selectStatement.close(); connection.close(); return amount; }}
The compiled Junit test inherits from the BankFixture class. The test code is as follows:
package davenkin.step1_failure;import davenkin.BankFixture;import org.junit.Test;import java.sql.SQLException;import static junit.framework.Assert.assertEquals;public class FailureBankServiceTest extends BankFixture{ @Test public void transferSuccess() throws SQLException { FailureBankDao failureBankDao = new FailureBankDao(dataSource); FailureInsuranceDao failureInsuranceDao = new FailureInsuranceDao(dataSource); FailureBankService bankService = new FailureBankService(dataSource); bankService.setFailureBankDao(failureBankDao); bankService.setFailureInsuranceDao(failureInsuranceDao); bankService.transfer(1111, 2222, 200); assertEquals(800, getBankAmount(1111)); assertEquals(1200, getInsuranceAmount(2222)); } @Test public void transferFailure() throws SQLException { FailureBankDao failureBankDao = new FailureBankDao(dataSource); FailureInsuranceDao failureInsuranceDao = new FailureInsuranceDao(dataSource); FailureBankService bankService = new FailureBankService(dataSource); bankService.setFailureBankDao(failureBankDao); bankService.setFailureInsuranceDao(failureInsuranceDao); int toNonExistId = 3333; bankService.transfer(1111, toNonExistId, 200); assertEquals(1000, getInsuranceAmount(2222)); assertEquals(1000, getBankAmount(1111)); }}
Run the test. The first test (transferSuccess) is successful, and the second test (transferFailure) fails.
Analysis Error because dataSource is called three times from FailureBankService, FailureBankDao, and FailureInsuranceDao. getConnection (), that is, we have created three different Connection objects, and Java Transactions Act on the Connection. Therefore, we have started three different transactions in three places, instead of the same transaction.
The first test was successful because no exception occurred during this process. Although the Connection submission mode is changed to manual submission in FailureBankService, because the two DAO s use their own Connection objects, the Connection in the two dao s is still the default automatic submission mode.
In the second test, we provided a non-existent insurance account id (toNonExistId) to cause an exception in the program, and then verified in the assertion statement that the two tables did not change, however, the test encountered an error in the second assertion statement. When an exception occurs, the amount in the bank account has been reduced. Although rollback occurs in the program, the rollback of the Connection in FailureBankService is called instead of the Connection in FailureInsuranceDao, the operation on the insurance account is not performed at all, so the insurance account is still 1000, but the bank account is changed to 800.
Therefore, in order to make the two DAO in the same transaction, we should use a Connection object throughout the transaction processing process. In the next article, we will discuss how to achieve transaction processing by sharing the Connection object.