1

We're building a new application in Spring MVC with Hibernate as persistence solution. There 're 2 solutions to approach the data layer:

1) In some cases the controller invokes the DAO layer directly. This is done because no business checks need to be performed. So we're bypassing the Service layer for such cases. Implementing a Service layer for this would turn up in just delegating methods to the DAO layer.

So we're doing the following: Controller -> DAO

2) In other cases we do need some business checks. For this, we use the conventional way:
Controller -> Service -> DAO

In Spring we need to demarcate a Transaction, therefore we put @Transaction annotation on all DAO methods. This works fine doing the Controller -> DAO way. But if we're doing the Controller -> Service -> DAO way, we also need to put a @Transaction annotation on the service method.

This means that we're having nested transactions in some cases. Is this a good approach? Do we need to create a new transaction (REQUIRES_NEW) on all DAO methods or rather use the existing transaction (REQUIRED) if one exists?

Can someone enlighten me on this?

4

1 回答 1

4

默认的传播策略REQUIRED

在您的第二种情况下REQUIRED,其工作方式几乎与没有@Transactionalat DAO 方法一样。唯一细微的区别在于异常回滚行为:当异常(导致事务回滚的那个)通过任何事务方法的边界时,事务被标记为“仅回滚”,而不仅仅是顶级方法,因此您将无法捕获从您的 DAO 方法引发的导致回滚的异常并进行事务提交。

REQUIRES_NEW在您的情况下,仅当您希望能够分别回滚内部和外部事务时才需要。

于 2013-08-11T13:40:08.503 回答