Skip to content

Instantly share code, notes, and snippets.

@wutingjia
Last active March 12, 2019 06:23
Show Gist options
  • Save wutingjia/f4b5f4ceef7c31477fcfca8ea4c75dd3 to your computer and use it in GitHub Desktop.
Save wutingjia/f4b5f4ceef7c31477fcfca8ea4c75dd3 to your computer and use it in GitHub Desktop.
Spring事务处理

事务处理.png
首先可以自己选择自己的数据源连接池等。
以JDBC和mybatis为例,使用DataSourceTranscationManager,不管哪种Manager都是PlatformTransactionManager的具体实现类。
使用注解方式:

@Bean("myDataSource")
DataSource DataSource(){
  return new DataSource();//类似
}

@Bean
public DataSourceTranscationManager dataSourceTranscationManager(@Autowired @Qulifier("myDataSource") DataSource source ){
  return new DataSourceTranscationManager(source);
}

在启动类添加注解 @EnableTranscationManagement
在需要开启事务的类或者方法上添加注解 @Transcational

@Transcational几个重要的属性:
枚举属性Propagation
REQUIRED:支持一个现有的事务,如果没有则新建一个。
SUPPORTS:支持一个现有的事务,如果没有则不做事务处理。
MANDATORY:支持一个现有的事务,如果没有则抛异常。
REQUIRES_NEW:新建一个事务,如果已存在则挂起已存在事务。
NOT_SUPPORTED:不做事务处理,如果已存在则挂起已存在事务。
NEVER:不做事务处理,如果已存在则抛出异常。
NESTED:如果有一个事务存在,做一个嵌入式的事务。

rollbackFor
rollbackForClassName
noRollbackFor
noRollbackForClassName
由名字可知,有着相似的作用。分别是异常名称 异常类型 已经是否回滚的选择,必须是Throwable及其子类。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment