Spring分为编程式事务和声明式事务
声明式事务:
Spring给了一个约定(AOP开发也给了我们一个约定),如果使用的是声明式事务,那么当你的业务方法不发生异常(或者发生异常,但该异常也被配置信息允许提交事务)时,Spring就会让事务管理器提交事务,而发生异常(并且该异常不被你的配置信息所允许提交事务)时,则让事务管理器回滚事务。
编程式需要自己手动写事务的回滚
配置位置文件
<?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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd 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"> <context:property-placeholder location="classpath:db.properties"/> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driver}"></property> <property name="url" value="${jdbc.url}"></property> <property name="password" value="${jdbc.password}"></property> <property name="username" value="${jdbc.username}"></property> </bean> <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.mapper"></property> <!-- 当使用自动注入的时候, --> <property name="sqlSessionFactoryBeanName" value="factory"></property> </bean> <!-- 声明式事务 --> <bean id="txmanager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置声明式事务 --> <tx:advice id="txadvice" transaction-manager="txmanager"> <!-- 设置那些方法需要事务管理 方法以in开头的 --> <tx:attributes> <tx:method name="in*"/> </tx:attributes> </tx:advice> <aop:config> <aop:aspect> <aop:pointcut expression="execution(* DeclarativeTransaction.*.*())" id="mypoint"/> <aop:before method="txadvice" pointcut-ref="mypoint"/> </aop:aspect> </aop:config> </beans>
原文:https://www.cnblogs.com/jflalove/p/11761338.html