JDBC Transaction Management
Spring provides a consistent programming model for different transaction implementations by providing Programmatic transaction manage-ment and Declarative transaction management, this section uses JDBC transactions as an example to introduce Spring transaction management.
5.3.1 Spring's support for transactions
A transaction is a unit of work for a group of Atomic (Atomic) operations. For database-accessed instances, it is a group of SQL commands, and all these SQL commands must be successfully executed, if not all SQL commands have been successfully executed for a certain reason (for example, one row of SQL statements has an error), all previously executed SQL commands will be revoked.
For example, if A customer transfers money from Bank A to Bank B, the action to be taken is to deduct money from the account of Bank A and add the transfer amount to the account of Bank B, both actions must be successful. If one action fails, the transfer fails.
Transactions must also maintain the consistency (Consistent) of the involved resources. For example, in the example of A bank account, the amount of money transferred between two accounts cannot be greater than the deposit amount of account. Each transaction must be Isolated from each other (Isolated). For example, an account A may have two transactions and make deposits and withdrawals at the same time. Basically, the two transactions do not need to be aware of each other's existence. The transaction must also be Durable, and after a transaction, the transaction must be recorded.
Here we will introduce how to use transaction management in JDBC. First, let's take a look at the Atomic Implementation of the transaction. In JDBC, you can operate the setAutoCommit () method of Connection. Given the false parameter, after a series of SQL statements are issued, execute the Connection commit () to send out the change. If an error occurs in the middle, execute rollback () to cancel all the changes. For example:
Try {
.....
Connection. setAutoCommit (false );
.....
// A series of SQL operations
Connection. commit ();
} Catch (SQLException ){
// If an error occurs, cancel all changes
Connection. rollback ();
}
The JDBC transaction management is encapsulated in Spring. The abstract key of Spring transaction management lies in the implementation of the org. springframework. transaction. PlatformTransactionManager interface:
Public interface PlatformTransactionManager {
TransactionStatus getTransaction (TransactionDefinition
Definition) throws TransactionException;
Void commit (TransactionStatus status)
Throws TransactionException;
Void rollback (TransactionStatus status)
Throws TransactionException;
}
The PlatformTransactionManager interface has many specific transaction implementation classes, such as cetcetransactionmanager, HibernateTransactionManager, JdoTransaction-Manager, and JtaTransactionManager. It relies on the PlatformTransactionManager interface and various technical implementations, spring allows developers to use consistent programming models in transaction management, even if different transaction management technologies are used.
TransactionException is an Unchecked Exception. Transaction failures are usually fatal errors. Spring does not force you to handle them, but lets you choose whether to capture exceptions.
The getTransaction () method transmits a TransactionStatus object back and forth based on a TransactionDefinition object. The instance of the TransactionDefinition interface defines the Isolation level, Propagation behavior, and Timeout of the transaction), Read-only, etc. TransactionStatus indicates a new transaction initiated or an existing transaction. You can use it to control the transaction execution or investigation status:
Public interface TransactionStatus {
Boolean isNewTransaction ();
Void setRollbackOnly ();
Boolean isRollbackOnly ();
}
Spring provides Programmatic transaction management and Declarative transaction management ):
L programmed Transaction Management
Programmed transaction management can clearly control the transaction boundary, that is, it allows you to implement the transaction start time, Undo operation time, end time, and so on, and achieve fine-grained transaction control.
L declarative Transaction Management
However, in most cases, transactions do not require fine-grained control, but adopt declarative transaction management. The advantage is that APIs related to Spring transaction management do not need to be involved in the program, from the perspective of the object, it does not know that it is being incorporated into the transaction management. When no transaction management is required, you only need to modify the settings on the settings file to remove the transaction management service.
5.3.2 JDBC programming Transaction Management Spring provides two programming-based transaction management methods: one is to use PlatformTransaction-Manager directly, and the other is to use org. springframework. transaction. support. transaction-Template.
Let's take a look at how to use PlatformTransactionManager. Here we use its implementation class DataSourceTransactionManager. You can rewrite the JdbcTemplateDemo project in Section 5.2.1 to have the transaction management function and modify the insert () of the UserDAO class () method: ProgrammaticTransactionDemo UserDAO. java
Package onlyfun. caterpillar;
Import java. util. Iterator;
Import java. util. List;
Import java. util. Map;
Import javax. SQL. DataSource;
Import org. springframework. dao. DataAccessException;
Import org. springframework. jdbc. core. JdbcTemplate;
Import org. springframework. jdbc.
Datasource. DataSourceTransactionManager;
Import org. springframework. transaction. TransactionDefinition;
Import org. springframework. transaction. TransactionStatus;
Import org. springframework. transaction.
Support. DefaultTransactionDefinition;
Public class UserDAO implements IUserDAO {
Private DataSourceTransactionManager transactionManager;
Private DefaultTransactionDefinition def;
Private JdbcTemplate jdbcTemplate;
Public void setDataSource (DataSource dataSource ){
JdbcTemplate = new JdbcTemplate (dataSource );
TransactionManager =
New cetcetransactionmanager (dataSource );
// Create a transaction Definition
Def = new DefaultTransactionDefinition ();
Def. setPropagationBehavior (
TransactionDefinition. PROPAGATION_REQUIRED );
}
Public void insert (User user ){
String name = user. getName ();
Int age = user. getAge (). intValue ();
TransactionStatus status =
TransactionManager. getTransaction (def );
Try {
JdbcTemplate. update ("insert into user (name, age )"
& Nbs