@Transactional method calling another method without @Transactional anotation?

前端 未结 4 1746
故里飘歌
故里飘歌 2020-12-02 05:16

I\'ve seen a method in a Service class that was marked as @Transactional, but it was also calling some other methods in that same class which were not marked as

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 05:32

    The inner method will affect the outer method if the inner method is not annotated with @Transactional.

    In case inner method is also annotated with @Transactional with REQUIRES_NEW, following will happen.

    ...
    @Autowired
    private TestDAO testDAO;
    
    @Autowired
    private SomeBean someBean;
    
    @Override
    @Transactional(propagation=Propagation.REQUIRED)
    public void outerMethod(User user) {
      testDAO.insertUser(user);
      try{
        someBean.innerMethod();
      } catch(RuntimeException e){
        // handle exception
      }
    }
    
    
    @Override
    @Transactional(propagation=Propagation.REQUIRES_NEW)
    public void innerMethod() {
      throw new RuntimeException("Rollback this transaction!");
    }
    

    The inner method is annotated with REQUIRES_NEW and throws a RuntimeException so it will set its transaction to rollback but WILL NOT EFFECT the outer transaction. The outer transaction is PAUSED when the inner transaction starts and then RESUMES AFTER the inner transaction is concluded. They run independently of each other so the outer transaction MAY commit successfully.

提交回复
热议问题