您应该将@Transactional放在DAO类和/或它们的方法中,还是更好地注释使用DAO对象调用的服务类?或者对两个“层”都加注释有意义吗?
当前回答
服务层是添加@Transactional注释的最佳位置,因为这里呈现的大多数业务逻辑都包含细节级用例行为。
假设我们将它添加到DAO,从服务调用2个DAO类,一个失败,另一个成功,在这种情况下,如果@Transactional不在服务上,一个DB将提交,另一个DB将回滚。
因此,我的建议是明智地使用这个注释,只在服务层使用。
Github项目- java-algos
其他回答
传统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类型间定义将实体语义(事务和持久性)与领域对象(基本上是字段和业务方法)分离开来。
通常,应该将事务放在服务层。
但是正如前面所述,操作的原子性告诉我们哪里需要注释。因此,如果你使用像Hibernate这样的框架,其中一个“save/update/delete/…”一个对象上的“modify”操作有可能修改几个表中的几行(因为通过对象图的级联),当然在这个特定的DAO方法上也应该有事务管理。
此外,Spring建议只在具体的类上使用注释,而不是在接口上使用。
http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html
事务注释应该放在所有不可分割的操作周围。
例如,你的呼叫是“change password”。它由两个操作组成
修改密码。 审计变更。 通过电子邮件通知客户端密码已更改。
那么在上面,如果审计失败,那么修改密码也应该失败吗?如果是这样,那么事务应该在1和2左右(因此在服务层)。如果电子邮件失败了(可能应该有某种故障安全措施,这样它就不会失败),那么它是否应该回滚更改密码和审计?
在决定将@Transactional放在哪里时,您需要询问这些问题。
最好把它放在服务层!这在我昨天看到的一篇文章中有清楚的解释!这是你可以查看的链接!
推荐文章
- Java 8接口方法中不允许“同步”的原因是什么?
- 如何找到Java堆大小和内存使用(Linux)?
- Spring引导——不是托管类型
- 使用Enum实现单例(Java)
- RabbitMQ与通道和连接之间的关系
- buildSessionFactory()配置方法在Hibernate中已弃用?
- Spring MVC -如何获得所有的请求参数在一个地图在Spring控制器?
- 如何在Java中按两个字段排序?
- 文件之间的差异。路径中的分隔符和斜杠
- 在方法参数中使用NotNull注释
- Spring MVC中处理可选参数的@RequestParam
- Tomcat:如何查找正在运行的Tomcat版本?
- “java”、“javaw”和“javaws”之间有什么区别?
- 将Date对象转换为日历对象
- 在Java中保存最后N个元素的大小有限的队列