Table of contents
1. Modify the business layer code
Second, the transaction manager
2. Introduce constraints in the configuration file
3. Perform transaction configuration
1. PlatformTransactionManager interface
2. TransactionDefinition interface
3. TransactionStatus interface
Related readings of previous columns & articles
1. Business management plan
The bottom layer of declarative transactions adopts AOP technology, and manually adding transactions at the service layer can solve the problems mentioned in the previous article.
1. Modify the business layer code
Add a SqlSessionTemplate object, let us try catch the business method, submit if there is no exception, and roll back if the exception is caught.
package com.example.service;
import com.example.dao.AccountDao;
import com.example.pojo.Account;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service
public class AccountService {
@Autowired
private AccountDao accountDao;
@Autowired
private SqlSessionTemplate sessionTemplate;
/**
*
* @param id1 转出人id
* @param id2 转入人id
* @param price 金额
*/
// 作用方法上时,该方法都将具有该类型事务的事务属性
public void transfer(int id1,int id2, double price){
try {
// 转出人减少余额
Account account1 = accountDao.findById(id1);
account1.setBalance(account1.getBalance() - price);
accountDao.update(account1);
// 模拟程序出错
int i = 1 / 0;
// 转入人增加余额
Account account2 = accountDao.findById(id2);
account2.setBalance(account2.getBalance() + price);
accountDao.update(account2);
sessionTemplate.commit();
}
catch (Exception e){
e.printStackTrace();
sessionTemplate.rollback();
}
}
}
2. Test
OK, you can see that the program is interrupted abnormally. Now watch what's going on in the database.
OK, you can see that Zhang San has not been deducted money here, so it is also possible to submit the transaction manually, but in this way we have too many try catches. Hence the transaction manager.
Second, the transaction manager
1 Introduction
Spring relies on the transaction manager for transaction management. The transaction manager is a notification class. We set the cut point for the notification class as a service layer method to complete automatic transaction management. Since different technologies operate databases, the methods for performing transaction operations are different. For example: JDBC commits transaction is connection.commit(), MyBatis commits transaction is sqlSession.commit(), so Spring provides multiple transaction managers.
transaction manager name | effect |
org.springframework.jdbc.datasource.DataSourceTransactionManager | A transaction manager for JDBC technology. Works with JDBC and MyBatis. |
org.springframework.orm.hibernate3.HibernateTransactionManager | For the transaction manager provided by the Hibernate framework. Works with the Hibernate framework. |
org.springframework.orm.jpa.JpaTransactionManager | The transaction manager provided for JPA technology. Applicable to JPA technology. |
org.springframework.transaction.jta.JtaTransactionManager | Spans multiple transaction management sources. It is suitable for implementing transaction control in two or more different data sources. |
We use MyBatis to operate the database, and then use DataSourceTransactionManager for transaction management.
2. Introduce constraints in the configuration file
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
3. Perform transaction configuration
Add configuration in the applicationContext.xml file
<!-- 事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 进行事务相关配置 -->
<tx:advice id = "txAdvice">
<tx:attributes>
<!-- 代表所有方法 -->
<tx:method name="*" />
</tx:attributes>
</tx:advice>
<!-- 配置切面 -->
<aop:config>
<!-- 配置切点 -->
<aop:pointcut id="pointcut" expression="execution(* com.example.service..*(..))"/>
<!-- 配置通知 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
</aop:config>
3. Transaction control API
All transaction managers implement the PlatformTransactionManager interface. Spring’s transaction control function is provided by three interfaces. These three interfaces are implemented by Spring. We rarely use them in development. We only need to understand their functions:
1. PlatformTransactionManager interface
PlatformTransactionManager is a transaction manager interface provided by Spring, and all transaction managers implement this interface. This interface provides three transaction operation methods:
- TransactionStatus getTransaction (TransactionDefinition definition): Get transaction status information.
- void commit (TransactionStatus status): transaction commit
- void rollback(TransactionStatus status): transaction rollback
2. TransactionDefinition interface
TransactionDefinition is the definition information object of the transaction, which has the following methods:
- String getName(): Get the transaction object name.
- int getIsolationLevel(): Get the isolation level of the transaction.
- int getPropagationBehavior(): Get the propagation behavior of the transaction.
- int getTimeout(): Get the timeout time of the transaction.
- boolean isReadOnly(): Gets whether the transaction is read-only.
3. TransactionStatus interface
TransactionStatus is the status interface of the transaction, which describes the status information of the transaction at a certain point in time. It has the following methods:
- void flush() refresh transaction
- boolean hasSavepoint() Gets whether there is a savepoint
- boolean isCompleted() Get whether the transaction is completed
- boolean isNewTransaction() Get whether it is a new transaction
- boolean isRollbackOnly() Get whether to roll back
- void setRollbackOnly() Set transaction rollback
Related readings of previous columns & articles
If you don’t know anything about the content of this issue, you can also go to see the content of previous issues. The following is a series of column articles such as Maven and Mybatis carefully crafted by bloggers in the past. Don’t miss it when you pass by! If it is helpful to you, please like it and bookmark it. Among them, some of the Spring columns are being updated, so they cannot be viewed, but they can be viewed after the bloggers have completed all the updates.
1. Maven series of columns
Maven Series Column | Maven project development |
Maven aggregation development [example detailed explanation --- 5555 words] |