【问题标题】:@Transactional propagation on private methods@Transactional 在私有方法上的传播
【发布时间】:2015-12-19 11:26:37
【问题描述】:

我有以下代码:

@Service
public class MyService implements IMyService {
    @Inject
    IAnotherService anotherService;
    // injects go here
    // some code
    @Transactional(isolation=Isolation.SERIALIZABLE)
    public Result myMethod() {
        // stuff done here
        return this.myPrivateMethod()
    } 

    private Result myPrivateMethod() {
         // stuff done here
         // multiple DAO SAVE of anObject
         anotherService.processSomething(anObject);
         return result; 
    }
}

@Service
public class AnotherService implements IAnotherService {
      // injections here
      // other stuff

      @Transactional(isolation=SERIALIZABLE)
      public Result processSomething(Object anObject) {
         // some code here
         // multiple dao save
         // manipulation of anObject
         dao.save(anObject);
      }
}
  1. @Transactional 行为是否会传播到 myPrivateMethod,即使它是私有的?
  2. 如果Runtime Exception 出现在processSomething() 上,并且从myPrivateMethod 调用processSomething,那么myPrivateMethodmyMethod 会回滚吗?
  3. 如果对 1 和 2 的回答是否定的,我怎样才能在不创建另一个 @Service 的情况下做到这一点?如何在 @Transactional 上下文中的公共服务方法中提取方法并调用多个私有方法?。
  4. isolation=Isolation.SERIALIZABLE 选项是 synchronized 方法的良好替代品吗?。

我知道这个问题已经得到解答,但我仍然有疑问。

【问题讨论】:

  • 到目前为止你找到的答案告诉你什么? 1. 是 2. 是 3. 不适用,因为 1 && 2 4. 不,因为它只有在事务容器中调用该方法时才有效。
  • stackoverflow.com/questions/4396284/… ---> 找到了一些可以部分回答我的问题的参考资料,但主要主题并不集中在与我相同的案例上。我真的必须确定事务注释是否真的适用于我的情况。对于问题 4:如果我强制 Propagation.MANDATORY?

标签: java spring transactions isolation


【解决方案1】:
  1. 如果从带有 @Transactional 注释的公共方法调用 myPrivateMethod,则会传播它。
  2. 如果第一个条件为 TRUE 是,它将回滚。
  3. 比较数据库的隔离级别和类方法的同步是一种误解。他们根本不应该被比较。如果您的方法将在多线程环境中使用,您应该同步方法(请注意,在某些情况下,拥有线程安全代码是不够的)。隔离级别 SERIALIZABLE 用于数据库级别。它是最严格的隔离级别,它可以在你运行一些查询时锁定很多表,在它完成之前,帮助你的数据不会变成一些不一致的状态。您应该确定您需要这种级别的隔离,因为这可能会导致性能问题。所以答案是否定的。

【讨论】:

    猜你喜欢
    • 2019-04-24
    • 2012-05-31
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    • 2011-05-22
    • 2013-06-25
    相关资源
    最近更新 更多