Spring Boot中的同步事务

Fab*_*ner 2 java spring-data-jpa spring-boot

在Springboot中,我称之为服务的每个服务都会打开一个事务,当服务返回时它将关闭该连接,但就我而言,我需要创建一个将同步运行的方法(该方法仅在非同步方法中运行),并且他需要无论是否打开了一个事务,OPEN和CLOSE事务都是独立的,并且仅当THAT方法抛出错误时,该方法中的每个SQL操作才会回滚。如果调用它的方法抛出错误,他将不会回滚同步方法所做的任何事情。

因此,我尝试使用此示例:

@Service
public class MyService {
    @Autowired
    private MyRepository myRepository;

    public void methodNotSyncronized(String arg1, String arg2){
        logger.debug("init method no syncronied");
        MyObjct myObj = myRepository.findOne(1);

        methodSyncronized(arg2);

        myRepository.save(myObj);   //If I got some error here everything that methodSyncronized did should remaining
        logger.debug("finish method no syncronied");
    }

    @Transactional(isolation = Isolation.SERIALIZABLE, propagation = Propagation.REQUIRES_NEW)
    private synchronized  String methodSyncronized(String arg){
        logger.debug("init method  syncronied");
        //Here I will insert or delete something    
    }

}
Run Code Online (Sandbox Code Playgroud)

但是,当我调试此代码时,我得到了:

o.h.e.t.internal.TransactionImpl         : begin
                       myService         : init method no syncronied
                       myService         : init method  syncronied
                       myService         : finish method no syncronied                     
o.h.e.t.internal.TransactionImpl         : committing
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题

还有一件事,即使我只将休眠打印的数字相加,我调用的每个服务也是如此:

o.h.e.t.internal.TransactionImpl         : begin                       
o.h.e.t.internal.TransactionImpl         : committing
Run Code Online (Sandbox Code Playgroud)

即使我将 @Transactional(readOnly = true)放在方法中

小智 5

它不起作用,因为Spring @Transaction method call by the method within the same class, does not work:这是Spring AOP(动态对象和cglib)的限制。

检查一下:Spring @Transaction方法