Spring事务
在业务层的接口中的方法上(直接在接口上也行,表示整个接口中的所有方法)加注解@Transactional
public interface AccountService {
@Transactional
public void Transfer(String name1,String name2,int salary);
}
然后数据源配置那里添加一个事务管理
@Bean
public PlatformTransactionManager platformTransactionManager(DataSource dataSource){
DataSourceTransactionManager dataSourceTransactionManager=new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource);
return dataSourceTransactionManager;
}
最后在Spring配置类中添加注解@EnableTransactionManagement(proxyTargetClass = true)
这样在进行一个双向操作时,即使两个操作之间出现了异常,也会同时回滚,不会出现一个因为在异常语句之后操作失败,而另一个操作成功
package com.itjh.service;
import com.itjh.mapper.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class AccountImpleService implements AccountService{
@Autowired
private Mapper mapper;
@Override
public void Transfer(String name1,String name2,int salary) {
mapper.outmoney(name1,salary);
int i= 1/0;
mapper.inmoney(name2,salary);
}
Spring事务参数:
@Transactional(rollbackFor = {IOException.class})
:当int i= 1/0;
换成执行一些异常时,事务将不会同时回滚,因此需要上面这个参数- 当前方法记得抛出异常,然后测试类因为调用这里,所以也别忘了抛出异常
package com.itjh.service;
import com.itjh.mapper.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
public class AccountImpleService implements AccountService{
@Autowired
private Mapper mapper;
@Override
public void Transfer(String name1,String name2,int salary)throws IOException {
mapper.outmoney(name1,salary);
if(true){throw new IOException();}
mapper.inmoney(name2,salary);
}
}
**结果:**抛异常上面代码正常执行,下面的无法执行,即没有同时回滚
于是,给@Transactional()
加上面说的参数就行,即要执行哪些异常,就把它加进去