java 使用 DAO 模式的利弊
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1748238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pros and cons of the use of the DAO pattern
提问by Sheldon
As I mention in the title, I'm interested to know what you (as experienced developers) think about the use of the DAO pattern, specifically within a web application. What advantages have you found and what consequences of its use have you disliked?
正如我在标题中提到的,我很想知道您(作为有经验的开发人员)对 DAO 模式的使用有何看法,特别是在 Web 应用程序中。您发现了哪些优点以及您不喜欢使用它的哪些后果?
采纳答案by MetroidFan2002
The problems with DAOs that I have seen is that they typically handle full objects all the time. This creates completely unneeded overhead that wouldn't exist with simple queries. For example, if a drop down is to be created off of database reference data, a DAO user may simply say: "Get me the collection of objects for this table where y ordered by z". Then, that data is used in the dropdown, but typically only for a key/value combination, ignoring everything else in the objects (created data, last user who updated it, whether or not it is active, etc) that was retrieved and mapped. Even if this massaging happens near the DAO call and the objects do not get stored as they are retrieved (which is typically not the case, unfortunately, the objects are often wrapped in a c:forEach (JSP) and iterated over to produce a drop down), it still creates unneeded database and network overhead, not to mention the temporary increase in memory to hold these objects.
我所看到的 DAO 的问题是它们通常一直在处理完整的对象。这会产生完全不需要的开销,而简单查询不会存在这些开销。例如,如果要根据数据库引用数据创建下拉列表,DAO 用户可能会简单地说:“给我获取这个表的对象集合,其中 y 按 z 排序”。然后,该数据在下拉列表中使用,但通常仅用于键/值组合,忽略检索和映射的对象中的所有其他内容(创建的数据、最后更新它的用户、它是否处于活动状态等) . 即使这种按摩发生在 DAO 调用附近并且对象在检索时不会被存储(通常情况并非如此,不幸的是,对象通常包装在 ac:forEach (JSP) 中并迭代生成下拉列表) ),
Now, this is not to say that a DAO can't be designed to retrieve a Map of reference data - it certainly can. But typically they're used for the full object mapping, which is not what is needed all the time. It is a strength when saving, but a weakness, IMO, when retrieving data - sure, you get all of it - but often you don't need all of it, and it just wastes memory, bandwidth and time.
现在,这并不是说 DAO 不能设计为检索参考数据的 Map——它当然可以。但通常它们用于完整的对象映射,这并不是一直需要的。这是保存时的优势,但在 IMO 检索数据时,这是一个弱点——当然,你会得到所有的——但通常你不需要所有的,它只会浪费内存、带宽和时间。
回答by bogertron
NOTE: you might find other shortcomings, but here is a quick list from my experience
注意:您可能会发现其他缺点,但这里是我的经验的快速列表
PROS:
优点:
- Common calls to retrieve objects.
- Once you have the general create/read/update/delete flow set, the general layout can be repeated for other DAOs.
- It also consolidates where the persistence specific portion of your code can go. Separates the business logic from other components of your code.
- 检索对象的常见调用。
- 一旦您设置了通用的创建/读取/更新/删除流程,就可以为其他 DAO 重复通用布局。
- 它还整合了代码的持久性特定部分可以去的地方。将业务逻辑与代码的其他组件分开。
CONS:
缺点:
- It is not the most flexible thing ever.
- If you want to lazy-load some child objects, then you are going to have to either intermingle the DAOs with other layers or take precaution when attempting to retrieve the lazy objects.
- If you handwrite the DAOs, then the code can become tedious and repetitive.
- 它不是有史以来最灵活的东西。
- 如果您想延迟加载某些子对象,那么您将不得不将 DAO 与其他层混合,或者在尝试检索延迟对象时采取预防措施。
- 如果您手写 DAO,那么代码可能会变得乏味和重复。
回答by Divyesh Kanzariya
Benefits of using DAO design pattern
使用 DAO 设计模式的好处
DAO or Data Access Object design pattern is a good example of abstraction and encapsulation object oriented principles. It separates persistence logic is a separate layer called Data access layer which enables application to react safely to change in Persistence mechanism. For example, if you shift from File-based persistence mechanism to Database, your change will be limited to data access layer and won't impact Service layer or domain Objects. Data Access Object or DAO pattern is pretty much standard in Java application being it core Java, web application or enterprise application. Following are couple of more benefits of using DAO pattern in Java application:
DAO 或数据访问对象设计模式是抽象和封装面向对象原则的一个很好的例子。它将持久性逻辑分开是一个单独的层,称为数据访问层,它使应用程序能够安全地对持久性机制中的变化做出反应。例如,如果您从基于文件的持久性机制转移到数据库,您的更改将仅限于数据访问层,不会影响服务层或域对象。数据访问对象或 DAO 模式在 Java 应用程序中非常标准,因为它是核心 Java、Web 应用程序或企业应用程序。以下是在 Java 应用程序中使用 DAO 模式的更多好处:
DAO design pattern also keeps coupling low between different parts of an application. By using DAO design pattern your View Layer is completely independent of DAO layer and only Service layer has the dependency on it which is also abstracted by using DAO interface.
DAO design pattern allows JUnit test to run faster as it allows to create Mock and avoid connecting to database to run tests. It improves testing because it's easy to write test with Mock objects, rather than an Integration test with the database. In the case of any issue, while running Unit test, you only need to check code and not database. Also shields with database connectivity and environment issues.
Since DAO pattern is based on interface, it also promotes Object oriented design principle "programming for interface than implementation" which results in flexible and quality code.
DAO 设计模式还保持应用程序不同部分之间的低耦合。通过使用 DAO 设计模式,您的视图层完全独立于 DAO 层,只有服务层依赖于它,这也是使用 DAO 接口抽象出来的。
DAO 设计模式允许 JUnit 测试运行得更快,因为它允许创建 Mock 并避免连接到数据库来运行测试。它改进了测试,因为使用 Mock 对象编写测试很容易,而不是使用数据库编写集成测试。在任何问题的情况下,在运行单元测试时,您只需要检查代码而不是数据库。还屏蔽了数据库连接和环境问题。
由于 DAO 模式是基于接口的,它也提倡面向对象的设计原则“为接口编程而不是实现”,从而产生灵活和高质量的代码。
回答by Pascal Thivent
The forces of the DAO pattern are that they allow you to create a nice abstraction layer of the actual storage system. They provide a more object-oriented view of the persistence layer and a clean separation between the domain and the code that will actually perform the data access (straight JDBC, persistence frameworks, ORM or even JPA).
DAO 模式的力量在于它们允许您为实际存储系统创建一个很好的抽象层。它们提供了更面向对象的持久层视图,并在域和实际执行数据访问的代码(直接 JDBC、持久性框架、ORM 甚至 JPA)之间进行了清晰的分离。
If I had to cite a weakness, well, I'd say it's another layer... But I guess this is the price to pay to not tie your code to the underlying persistence API.
如果我不得不引用一个弱点,好吧,我会说它是另一层……但我想这是不将您的代码绑定到底层持久性 API 所付出的代价。
回答by Malcolm Featonby
We have seen some real benefit in introducing a DAO pattern into our implementation. This due mainly to the clear separation between database interface and implementation. We have observed the following benefits:
我们已经看到在我们的实现中引入 DAO 模式的一些真正好处。这主要是由于数据库接口和实现之间的明确分离。我们观察到以下好处:
- Abstraction for actual database access implementation separates the data access strategy from the user business logic. This has allowed us to choose a short term (Spring JDBC Template) implementation strategy for the initial project phase with the option to move to IBATIS or Hibernate at a later date. (A choice we are not in a position to make at this time.)
- The separation introduces significant testability benefits in that the entire data access implementation can be mocked out in unit testing. (This is probably the biggest benefit)
- Combining this with Spring allows us to inject any DB implementation into the system we choose (although this possibly says more about DI than the DAO pattern).
- 实际数据库访问实现的抽象将数据访问策略与用户业务逻辑分开。这使我们能够为初始项目阶段选择一个短期(Spring JDBC 模板)实现策略,并可以选择在以后迁移到 IBATIS 或 Hibernate。(我们目前无法做出选择。)
- 这种分离带来了显着的可测试性优势,因为可以在单元测试中模拟整个数据访问实现。(这可能是最大的好处了)
- 将其与 Spring 相结合允许我们将任何 DB 实现注入到我们选择的系统中(尽管这可能更多地说明了 DI 而不是 DAO 模式)。
One issue that we encountered, and this may be due to a lack of clarity of design on our part is the "inclination" to reuse the Data Value Objects published out of the database as Transfer Objects between the subsequent abstraction layers in the architecture. Our solution after some pain was to have a value object per layer (i.e. to not reuse the database value objects in subsequent architectural layers).
我们遇到的一个问题,这可能是由于我们缺乏设计的清晰度,是“倾向于”重用从数据库发布的数据值对象作为体系结构中后续抽象层之间的传输对象。经过一番痛苦之后,我们的解决方案是每层都有一个值对象(即不要在后续架构层中重用数据库值对象)。
回答by BalusC
Pro: abstract separation.
Con: boilerplate code (thank god for code generators/templates and ORM's).
优点:抽象分离。
缺点:样板代码(感谢上帝提供代码生成器/模板和 ORM)。
回答by rsp
PRO
专业版
- single point of definition for DB table - Object attribute mapping
- transparent possibility for DAO implementations to other storage types
- develop an interface pattern all DAO's follow
- developing a more or less standard JUnit test class for DAO's results in better test coverage
- full control over specifics
- no performance loss due to an overly generic solution
- DB表的单点定义 - 对象属性映射
- DAO 实现到其他存储类型的透明可能性
- 开发所有 DAO 遵循的接口模式
- 为 DAO 的结果开发或多或少的标准 JUnit 测试类以获得更好的测试覆盖率
- 完全控制细节
- 没有由于过于通用的解决方案而导致的性能损失
CON
康
- less "sexy" than using the latest framework
- developers don't get to invent their own wheels (might be a PRO :-))
- 不如使用最新框架“性感”
- 开发人员不会发明自己的轮子(可能是专业人士:-))
As with most development patterns, using DAO's takes some time to get used to. With experience comes the benefits of more robust code and developers that know why things work, not just that it seems to. That last point is the biggest advantage for me.
与大多数开发模式一样,使用 DAO 需要一些时间来适应。经验带来的好处是更健壮的代码和知道事情为什么会起作用的开发人员,而不仅仅是它看起来如此。最后一点对我来说是最大的优势。
Caveat, depending on your situation using a persistence framework might be a good alternative to coding your own DAO's.
警告,根据您的情况,使用持久性框架可能是编写您自己的 DAO 的一个很好的替代方案。
回答by djna
What alternative are you considering?
你在考虑什么替代方案?
It seems pretty obvious that placing responsibility for persistence somewhere other than the presentation tier will usually be good, just from arguments of clarity of responsibility and reuse. I instinctively go for a three layer approach: Presentation, Service, Persistence. Confess to having been doing it this way for so long that I can't aduce evidence of pain suffered by not doing it that way. To me it seems "obvious" that having a single layer which understands the persistence mechanism must simplify testing, ease maintenance and give a good separation of concerns.
很明显,将持久性的责任放在表现层以外的其他地方通常是好的,只是从责任和重用的清晰度的论点来看。我本能地采用三层方法:展示、服务、持久性。承认我一直这样做很长时间,以至于我无法证明不这样做会遭受痛苦。对我来说,具有理解持久性机制的单一层必须简化测试、简化维护并提供良好的关注点分离,这似乎“显而易见”。
So that leaves the question of exactly how to do the persistence layer. My default assumption would be to use JPA (or similar frameworks). I do view this as a sophisticated example of DAO.
所以这就留下了究竟如何做持久层的问题。我的默认假设是使用 JPA(或类似框架)。我确实认为这是 DAO 的一个复杂示例。
So I see two costs of DAO. First you need to invest in your program structure, its design. For trivial cases this may feel like overkill. Second if you use a framework that implements DAO for you there is a learning curve. Compared with just writing the JDBC code directly this is another investment.
所以我看到了 DAO 的两个成本。首先你需要投资你的程序结构,它的设计。对于微不足道的情况,这可能感觉有点矫枉过正。其次,如果您使用为您实现 DAO 的框架,则需要学习曲线。与直接编写JDBC 代码相比,这是另一项投资。


