【问题标题】:Spring Hibernate JPA @Transaction(Propagation.REQUIRES_NEW) can't find objectSpring Hibernate JPA @Transaction(Propagation.REQUIRES_NEW)找不到对象
【发布时间】:2017-07-10 14:04:41
【问题描述】:

我在盯着显示器 5 小时后问这个问题

我有以下格式的代码

@Transaction(readmode=true)
class SomeServiceClass {
    @Autowired
    SubServiceClassA subServiceClassA;

    @Autowired
    SubServiceClassB subServiceClassB;

    public void doSomething() {
        Long id = subServiceClassA.performSave();

        subServiceClassB.performAction(id);
    }
}

我持久化一个对象并返回 id。

@Service
class SubServiceClassA {
    @Transactional(propagation=Propagation.REQUIRES_NEW)
    public Long performSave() {
        SomeObj someObj = someRepository.save(SomeObj someObj);
        return someObj.getId();
    }
}

稍后在一个单独的REQUIRES_NEW 事务中,我尝试对新保存的对象做一些事情。

@Service
class SubServiceClassB {
    @Transactional(propagation=Propagation.REQUIRES_NEW)
    public void performAction(Long id) {
        SomeObj someObj = someRepository.find(id);
        // someObj is null here!!! :(
    }
}

我的理解是这段代码应该可以工作,因为保存的对象在一个单独的 bean 中的 REQUIRES_NEW 事务中。

我的问题是这段代码在我的本地环境中运行良好。当我将它上传到生产设置时,我得到一个 NPE,因为 someObjnull。 (我们用的是gradle,所以依赖应该是一样的)

如果我能得到任何关于为什么这可能不起作用的指示,我将不胜感激。

【问题讨论】:

  • 代码退出 SubServiceClassA .performSave() 方法后是否触发了插入查询?
  • 插入代码为someRepository.save(SomeObj someObj);。它在SubServiceClassA. performSave() 方法中
  • 尝试从另一个方法调用 subServiceClassB.performAction(id)。 @Transaction(readmode=true)的目的是什么
  • SomeServiceClass 除了需要@TransactionaldoSomething 之外还有其他方法。 subServiceClassB.performAction(id) 应该采用不同的方法有什么原因吗?无论如何它应该在一个新的交易中......
  • 我的意思是:退出 performSave() 时是否触发了实际的 SQL 查询?试图了解事务是否实际提交到 db

标签: java spring hibernate jpa transactions


【解决方案1】:

找到解决办法

我想我是在没有额外信息的情况下发布的

我的 ServiceB 类中的代码是

@Service
class SubServiceClassB {
    @Transactional(propagation=Propagation.REQUIRES_NEW, readonly=true)
    public void performAction(Long id) {
        SomeObj someObj = someRepository.find(id);
        // someObj is null here!!! :(
    }
}

问题是我正在将 ServiceA 中的对象写入主数据库,但从从数据库读取。显然,设置readonly=true 会强制服务器从slaveDB 读取,但是新持久化的对象还没有被复制到slave DB。

删除readonly=true 后,一切正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-19
    • 1970-01-01
    相关资源
    最近更新 更多