Propagation.REQUIRES_NEW does not create a new transaction in Spring with JPA

后端 未结 3 751
猫巷女王i
猫巷女王i 2020-12-24 15:16

I have the following scenario. I am using JPA, Spring:

@Autowired
SampleService service;

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Ex         


        
相关标签:
3条回答
  • 2020-12-24 15:28

    Spring transactions are proxy-based. Here's thus how it works when bean A causes a transactional of bean B. A has in fact a reference to a proxy, which delegates to the bean B. This proxy is the one which starts and commits/rollbacks the transaction:

    A ---> proxy ---> B
    

    In your code, a transactional method of A calls another transactional method of A. So Spring can't intercept the call and start a new transaction. It's a regular method call without any proxy involved.

    So, if you want a new transaction to start, the method createSampleObject() should be in another bean, injected into your current bean.

    This is explained with more details in the documentation.

    0 讨论(0)
  • 2020-12-24 15:41

    My guess is that since both methods are in the same bean, the Spring's AOP does not have a chance to intercept the create/updateSampleObject method calls. Try moving the methods to a separate bean.

    0 讨论(0)
  • 2020-12-24 15:43

    Please create a bean for the same class(self) and use bean.api(which requires requires_new). It works.

    0 讨论(0)
提交回复
热议问题