Spring @Transactional没有回滚bean属性

时间:2016-04-06 21:50:53

标签: java spring transactions spring-transactions transactional

修改bean属性未使用spring @Transactional

回滚

TestController.java

@RestController
public class TestController {

    @Autowired
    private TestService testService;
    @Autowired
    private TestBean testBean;

    @RequestMapping(value = "/test")
    public String testTransaction() {
          try{
              testService.testTransaction();
          }catch(Exception e){
              System.out.println("After exception: " + testBean.getAttribute());
          }
          return "test"
    }
}

TestService.java

@Service
public class TestService {

    @Autowired
    private TestBean testBean;

     @Transactional(rollbackFor = Exception.class)
     public void testTransaction() {
          testBean.increment();
          System.out.println("Before exception: " + testBean.getAttribute());
          throw new UnexpectedRollbackException("unexpected exception");
     }
}

TestBean.java

@Component
public class TestBean {

     private int attribute = 0;

     public TestBean() {
     }

     public void increment () {
          attribute++;
     }

     public int getAttribute() {
          return attribute;
     }
}

控制台日志

Before exception: 1
After exception: 1

我想知道为什么属性值没有回滚到0(它的初始值)。

2 个答案:

答案 0 :(得分:0)

您无法以这种方式测试@Transactional注释,您需要数据库连接。 回滚过程在数据库上,而不在对象或bean上(如果有,我不知道)。首先获取数据库连接,然后在服务中键入一些与数据库相关的代码,如obj.save()或obj.update(other_obj),同样在此方法中抛出异常。在Controller中,调用您的服务方法并控制您自己的数据库是否保存数据。

Spring使用RunTimeException或其子类的回滚机制。

你可以找一些我的春季训练here

答案 1 :(得分:0)

@Transactional管理数据库事务。通常,您有一个数据源bean。此bean管理与数据库的连接。在这个bean的顶部,你有一个事务管理器。另一个bean与@Transactional注释一起检查应该在事务中运行的方法。如果您的方法以异常结束,则事务管理器将执行基础数据库事务的回滚。

您可以在文档here

中找到更多详细信息