سؤال

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?

هل كانت مفيدة؟

المحلول

The default propagation strategy (REQUIRED) is a reasonable choice for the most of scenarios, therefore you can safely use it unless you have some very special requirements.

In your second case REQUIRED would work almost the same way as if there were no @Transactional at DAO methods. The only subtle difference is in rollback-on-exception behavior: transaction is marked as "rollback only" when exception (the one that causes transaction rollback) passes a border of any transactional method, not just a top-level one, so that you won't be able to catch a rollback-causing exception thrown from your DAO method and make transaction commit.

REQUIRES_NEW in your case is only needed if you want to be able to rollback inner and outer transactions separately.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top