<!-- 事務管理器 --> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 事務增強 --> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED"/> <tx:method name="insert*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="del*" propagation="REQUIRED"/> <tx:method name="find*" propagation="NOT_SUPPORTED"/> <tx:method name="search*" propagation="NOT_SUPPORTED"/> <tx:method name="*" propagation="SUPPORTS" read-only="true"/> </tx:attributes> </tx:advice>
propagation:事務傳播機制
REQUIRED(默認值)
REQUIRES_NEW 、MANDATORY、NESTED
SUPPORTS NOT_SUPPORTED、NEVER
isolation:事務隔離等級 DEFAULT(默認值)
READ_COMMITTED READ_UNCOMMITTED
REPEATABLE_READ SERIALIZABLE
timeout:事務超時時間,允許事務運行的最長時間,以秒為單位。默認值為-1,表示不超時
read-only:事務是否為只讀,默認值為false
rollback-for:設定能夠觸發回滾的異常類型
Spring默認只在拋出runtime exception時才標識事務回滾 可以通過全限定類名指定需要回滾事務的異常,多個類名用逗號隔開
no-rollback-for:設定不觸發回滾的異常類型
Spring默認checked Exception不會觸發事務回滾 可以通過全限定類名指定不需回滾事務的異常,多個類名用英文逗號隔開
<!-- 華麗的分割線--!>
在Spring配置文件中配置事務管理類,並添加對注解配置的事務的支持
<bean id="txManager" class="org.springframework.jdbc.datasource .DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:annotation-driven transaction-manager="txManager"/>
使用@Transactional為方法添加事務支持
@Transactional @Service("userService") public class UserServiceImpl implements UserService { …… @Transactional(propagation = Propagation.SUPPORTS) public List<User> findUsersWithConditions(User user) { 。。。。。。。。。。。。。。。。。。。。 }}