在DAO中使用Spring MVC和Hibernate的正确方法是什么,服务层架构 [英] What is the right way to use spring MVC with Hibernate in DAO, service layer architecture

查看:24
本文介绍了在DAO中使用Spring MVC和Hibernate的正确方法是什么,服务层架构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 DAO 类中使用带有 Hibernateaosupport 的 Spring MVC.这里很困惑从哪里开始事务,应该在服务层还是DAO层?

I am using Spring MVC with Hibernatedaosupport for my DAO classes. Confused here where to start the transaction, whether it should be in service layer or DAO layer?

我的视图与服务层交互.DAO 被注入到服务中.

My view interacts with Service layer. DAO's are injected into services.

在 DAO、服务层架构中使用 Spring MVC 和 Hibernate 的正确方法是什么?

What is the right way to use Spring MVC with Hibernate in DAO, service layer architecture?

推荐答案

恕我直言,事务应该转到服务层.通常,一个业务事务由多个查询和更新组成.如果你只将@Transactional放在DAO层,每个查询和更新都会在一个单独的事务中运行,这有效地违背了事务的目的.

IMHO the transactions should go to service layer. Typically one business transaction consists of several queries and updates. If you place @Transactional only on DAO layer, each query and update will run in a separate transaction, which effectively defeats the purpose of transactions.

但是如果服务是@Transactional,当web层进入服务层时,每个数据库交互都会加入一个主事务.请注意,在这种情况下,如果 web 层运行多个服务方法,它们中的每一个都将在单独的事务中运行(相同的问题向上移动一级).但是将 @Transactional 放在 web 层可能会引入意想不到的副作用,如 N+1 问题,否则会被发现.因此,尽量将一项业务事务保留在 Web 层调用的一种服务方法中.

But if services are @Transactional, each database interaction joins one main transaction started when web layer entered the service layer. Note that in this case if web layer runs several service methods, each of them will run in a separate transaction (the same problem shifted one level up). But placing @Transactional in web layer might introduce unexpected side effects like N+1 problem, which would have been caught otherwise. Thus try to keep one business transaction in one service method called from web layer.

这篇关于在DAO中使用Spring MVC和Hibernate的正确方法是什么,服务层架构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆