【发布时间】:2019-03-16 18:48:03
【问题描述】:
在 Springboot 中,我调用它的每个服务都会打开一个事务,当服务返回时它会关闭该连接,但在我的情况下,我需要创建一个同步运行的方法(此方法只会在非同步方法中运行)和他需要打开和关闭一个独立的事务,如果有一个打开与否,并且该方法中的每个 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
}
}
但是当我调试这段代码时,我得到了:
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
我该如何解决这个问题
还有一件事,我调用的每个服务,即使我只对休眠打印的数字求和:
o.h.e.t.internal.TransactionImpl : begin
o.h.e.t.internal.TransactionImpl : committing
即使我将 @Transactional(readOnly=true) 放入方法中
【问题讨论】:
-
您对
synchronized的强调最初使我对您要完成的工作感到困惑-但似乎根本问题是Propagation.REQUIRES_NEW没有创建/提交自己的事务,而是重用现有事务?您的应用程序中的事务管理是如何配置的?
标签: java spring-boot spring-data-jpa