@Transactional传播私人方法

时间:2015-09-22 13:03:15

标签: java spring transactions isolation

我有以下代码:

@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()processSomething调用myPrivateMethodmyPrivateMethodmyMethod会回滚吗?
  3. 如果对1和2的答案为否,那么如何在不创建另一个@Service的情况下实现这一目标?如何在@Transactional上下文中的公共服务方法中提取方法并调用多个私有方法?
  4. isolation=Isolation.SERIALIZABLE选项是synchronized方法的一个很好的替代方案吗?
  5. 我知道这已经回答了,但我仍然怀疑。

1 个答案:

答案 0 :(得分:3)

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