一、搭建测试事务环境
1、模拟转账流程,创建表:
2、spring核心配置
#DataSource.properities
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/spring_jdbc_template_test
jdbc.username=root
jdbc.password=syp2017
<!-- 扫描包下的所有注解 -->
<context:component-scan base-package="com.jdbc"></context:component-scan>
<context:property-placeholder location="com/jdbc/tx/DataSource.properties"></context:property-placeholder>
<!-- 创建DataSource对象 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 创建JdbcTemplate对象 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg name="dataSource" ref="dataSource"></constructor-arg>
</bean>
3、创建AccountDao类,并配置
public class AccountDao {
@Resource(name="jdbcTemplate")
private JdbcTemplate jdbcTemplate;
public void reduce() {
jdbcTemplate.update("update account set money=money-10 where user='红红'");
}
public void add() {
jdbcTemplate.update("update account set money=money+10 where user='小明'");
}
}
<!-- 配置AccountDao -->
<bean id="accountDao" class="com.jdbc.tx.AccountDao"></bean>
4、创建AccountService类并配置
public class AccountService {
@Resource(name="accountDao")
private AccountDao accountDao;
public void doAccount() {
accountDao.reduce();
accountDao.add();
}
}
<!-- 配置AccountService -->
<bean id="accountService" class="com.jdbc.tx.AccountService"></bean>
二、配置方式使用事务
<!-- 第一步 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入dataSource -->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 第二步 配置事务增强 -->
<tx:advice id="txadvice" transaction-manager="transactionManager">
<!-- 做事务操作 -->
<tx:attributes>
<!-- 设置进行事务操作的方法匹配规则 以do开头的方法-->
<tx:method name="do*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- 第三步 配置切面 -->
<aop:config>
<!-- 切入点 -->
<aop:pointcut expression="execution(* com.jdbc.tx.AccountService.*(..))" id="pointcut"/>
<!-- 切面 -->
<aop:advisor advice-ref="txadvice" pointcut-ref="pointcut"/>
</aop:config>
其他项目修改切入点和tx:method
三、注解方式使用事务
<!-- 第一步配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 第二步 开启事务注解 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
//第三步 在AccountService加注解
@Transactional
public class AccountService {
@Resource(name="accountDao")
private AccountDao accountDao;
public void doAccount() {
accountDao.reduce();
accountDao.add();
}
}