编程式事务
声明式事务(最常用)
注意
要使用Spring进行事务管理,需要配置Spring的事务管理器
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg ref="dataSource" />
</bean>
在配置文件中导入Spring中对事务的约束
xmlns:tx="http://www.springframework.org/schema/tx"
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
开启Spring事务管理
<!--开启Spring事务管理-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
配置事务通知,也就是说什么样的操作需要事务
<!--配置事务通知-->
<tx:advice id="interceptor" transaction-manager="transactionManager">
<tx:attributes>
<!--配置方法要使用的事务隔离等级和传播特性,一般使用默认的即可-->
<tx:method name="*" propagation="REQUIRED" isolation="DEFAULT"/>
</tx:attributes>
</tx:advice>
配置AOP
<aop:config>
<aop:pointcut id="transaction" expression="execution(* com.pbx.mapper.*.*(..))"/>
<aop:advisor advice-ref="interceptor" pointcut-ref="transaction"/>
</aop:config>
测试
test是在一个业务实现类中的具体业务处理
public void test() {
UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
mapper.addUser(new User(5, "吴尊", "1235"));
mapper.deleteUser(12);
for (User user : mapper.getAllUser()) {
System.out.println(user);
}
}
测试类,因为没有12条数据,所以删除时会报错
@Test
public void test4() {
UserMapperImpl2 bean = context.getBean("userMapperImpl2", UserMapperImpl2.class);
bean.test();
}
执行完之后,可以看到id为5的数据并没有添加到数据库中
原文:https://www.cnblogs.com/primabrucexu/p/14058907.html