【问题标题】:Spring @Transactional not rollbacking a bean attributeSpring @Transactional 不回滚 bean 属性
【发布时间】:2016-04-06 21:50:53
【问题描述】:

修改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(它的初始值)。

【问题讨论】:

    标签: java spring transactions spring-transactions transactional


    【解决方案1】:

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

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

    你可以找到我的一些春训here

    【讨论】:

    • 我已经测试了参数传递的变量(testTransaction(int n))的回滚,它已经工作了...... bean属性的问题
    • 我不知道@Transactional注解对你实现的bean的影响。但是如果你像我说的那样实现你的代码。它可能会完全工作。也许,您使用的 int 变量会在您重新启动项目时重新生成。所以当应用程序重新启动时,n 变量可以更改为 1 或 0。
    【解决方案2】:

    @Transactional 管理数据库事务。通常,您有一个数据源 bean。该 bean 管理与您的数据库的连接。在这个 bean 之上,您有一个事务管理器。它是另一个 bean,它与 @Transactional 注释一起检查您应该在事务中运行的方法。如果您的方法以异常结束,事务管理器将对底层数据库事务进行回滚。

    您可以在文档here中找到更多详细信息

    【讨论】:

      猜你喜欢
      • 2017-04-14
      • 2018-11-08
      • 2019-06-30
      • 2016-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-16
      • 2018-09-27
      相关资源
      最近更新 更多