您应该将@Transactional放在DAO类和/或它们的方法中,还是更好地注释使用DAO对象调用的服务类?或者对两个“层”都加注释有意义吗?


当前回答

此外,Spring建议只在具体的类上使用注释,而不是在接口上使用。

http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html

其他回答

我认为事务属于服务层。它了解工作单元和用例。如果将几个dao注入到需要在单个事务中协同工作的服务中,这是正确的答案。

我将@Transactional放在@Service层,并设置rollbackFor任何异常和readOnly以进一步优化事务。

默认情况下@Transactional将只查找RuntimeException(未检查的异常),通过将回滚设置为exception. class(已检查的异常),它将回滚任何异常。

@Transactional(readOnly = false, rollbackFor = Exception.class)

参见已检查异常和未检查异常。

此外,Spring建议只在具体的类上使用注释,而不是在接口上使用。

http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html

传统Spring体系结构的正确答案是将事务语义放在服务类上,原因其他人已经描述过了。

An emerging trend in Spring is toward domain-driven design (DDD). Spring Roo exemplifies the trend nicely. The idea is to make the domain object POJOs a lot richer than they are on typical Spring architectures (usually they are anemic), and in particular to put transaction and persistence semantics on the domain objects themselves. In cases where all that's needed is simple CRUD operations, the web controllers operate directly on the domain object POJOs (they're functioning as entities in this context), and there's no service tier. In cases where there's some kind of coordination needed between domain objects, you can have a service bean handle that, with @Transaction as per tradition. You can set the transaction propagation on the domain objects to something like REQUIRED so that the domain objects use any existing transactions, such as transactions that were started at the service bean.

从技术上讲,这种技术使用了AspectJ和<context:spring-configured />。Roo使用AspectJ类型间定义将实体语义(事务和持久性)与领域对象(基本上是字段和业务方法)分离开来。

我更喜欢在方法级的服务层上使用@Transactional。