【问题标题】:Why Grails/Spring transactional behavior not working in this case?为什么 Grails/Spring 事务行为在这种情况下不起作用?
【发布时间】:2017-09-24 03:27:50
【问题描述】:

我有一个 grails (2.5.2) 应用程序,具有 mysql 和 NoSQL 交互。有一个 main/principal 服务方法调用另外 2 个方法:

class mainService {

  static transactional = false
  NoSQLDataAccessService noSQLDataAccessService

  // main/principal method
  @Transactional
  void save(json){

    // (1) creating domain entities from json
    addNewDomainEntities(entities)

    // (2)
    noSQLDataAccessService.set(json)
  }

  @Transactional
  void addNewDomainEntities(entities){
  // save the entities in a mysql schema and use save(flush:true) 
  // because i need the generated id's
  }

}

如您所见,此 mainService 创建新的域实体 (1),刷新会话以获取 id。然后,我调用将 json 存储在 NoSQL 模式中的其他服务方法 (2):

class NoSQLDataAccessService(){

  static transactional = false

  void set(json){
    try{
    // save the json in a NoSQL schema
    } catch(Exception ex){
      // if fails, i log the exception and throws it again
      throws ex
    }
  }
}

但是,有时 noSQLDataAccessService.set() 会因外部原因失败并且之前创建的实体仍然存在于 mysql 数据库中。(这是问题所在)

包含所有这些程序执行的保存方法被标记为@Transactional,因此如果 noSQLDataAccessService.set() 抛出异常,则不应应用所做的所有更改,因为回滚。我是对的?

【问题讨论】:

    标签: spring hibernate grails


    【解决方案1】:

    您可能必须抛出 RuntimeException,而不是 Exception,才能按照 this StackOverflow conversation 强制回滚。而不是:

    throws ex
    

    你可以试试:

    throw new RuntimeException(ex)
    

    此外,我建议您明确说明您的事务隔离。也许是这样的:

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.SERIALIZABLE)
    

    【讨论】:

      猜你喜欢
      • 2017-11-26
      • 2010-12-29
      • 1970-01-01
      • 2021-08-05
      • 2011-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多