1.事务管理器的声明
<!-- 事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean>
2. 编码式事务管理
<!-- 编码式事务,Spring事务模板 --> <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate"> <property name="transactionManager" ref="transactionManager" /> </bean>
/** * 编码型事务测试 */ public void killUser(final int userId) { txTemplate.execute(new TransactionCallback<Object>() { @Override public Object doInTransaction(TransactionStatus transactionStatus) { try { User user = userMapper.selectUserByID(userId); System.out.println(user.getUsername() + " was killed!"); } catch (RuntimeException e) { // 事务回滚 transactionStatus.setRollbackOnly(); throw e; } return null; } }); }
3.配置式事务
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <!-- 如果不显示的指定transaction-manager,则默认使用id为transactionManager的bean --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- method name表示已trick开头的方法 --> <tx:method name="trick*" propagation="REQUIRED"/> <tx:method name="*" propagation="REQUIRED" read-only="true"/> <!-- name 需要匹配的方法名 --> <!-- isolation 事务隔离级别 --> <!-- propagation 事务传播规则,有如下几种 --> <!-- MANDATORY 表示方法必须在事务中运行,否则抛出异常 --> <!-- NESTED 如果以存在事务,方法会在嵌套事务中运行,如果不存在,则是一个新事务 --> <!-- NOT SUPPORTED 该方法不能运行在事务中,否则抛出异常 --> <!-- REQUIRED 该方法必须运行在事务中,如果不存在,则开始新事务 --> <!-- REQUIRES_NEW 每次都开始一个新事务 --> <!-- SUPPORTS 方法不需要事务,但如果有事务则在事务中运行 --> <!-- read-only 是否将事务设置为只读,只能在新事务生效,数据库可以据此进行优化 --> <!-- rollback-for 设置哪些异常事务会回滚 --> <!-- no-rollback-for 设置哪些异常事务不会回滚 --> <!-- 默认的回滚策略是事务遇到检查型异常会回滚,RuntimeException不会回滚 --> <!-- timeout 事务超时回滚时间,单位是秒 --> <tx:method name="nothing*" isolation="READ_COMMITTED" propagation="MANDATORY" read-only="true" rollback-for="Exception" timeout="60"/> </tx:attributes> </tx:advice> <!-- 将事务定义为切面 --> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* *..UserServiceIntf.*(..))"/> </aop:config> </beans>
4.注解式事务
<!-- 开启注解式事务 --> <tx:annotation-driven transaction-manager="transactionManager" />
@Override @Transactional(propagation = Propagation.REQUIRED, readOnly = true) public void buyTicket(int userId) { User user = userMapper.selectUserByID(userId); if (user.getUserAge() < 18) System.out.println("It's free for people who is under 18 years of age"); else System.out.println("You should buy a ticket"); }