我应该在 DAO 中传入或封装连接吗?
将连接封装在 DAO 内(即让 DAO 创建或检索连接然后关闭)更好,还是将连接传递到 DAO 并在 DAO 外部的代码中处理详细信息更好?
追问:如果将连接封装在DAO中,如何管理关闭连接?
Is it better to encapsulate the connection inside a DAO, ie have the DAO create or retrieve the connection and then close, or is better to pass the connection into the DAO and handle the details in code external to the DAO?
Follow-up: How do you mange closing connections if you encapsulate the connection inside the DAO?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
DAO 应该执行 CRUD 操作并对调用者隐藏这些操作。所以你应该封装连接。
另一方面,如果上层正在协调 DAO(例如事务),那么您还可以将连接传递到 DAO(并在打开它的同一级别关闭它,而不是在 DAO 中)。
底线是......这实际上取决于应用程序每一层的职责。调用者是否应该关心 DAO 在哪里检索数据?如果没有,则封装连接。
The DAO should do CRUD operations and hide those operations from the callers. So you should encapsulate the connection.
On the other hand, if the upper levels are coordinating the DAOs (e.g. transactions) then you also could pass the connection into the DAOs (and close it at the same level you opened it, not in the DAOs).
Bottom line is... it really depends on the responsibility that each layer of your application has. Should the callers care where the DAOs are retrieving the data or not? If not, then encapsulate the connections.
我想你已经回答了你自己的问题。基本设计模式解释了 DAO 应该创建/检索连接(例如通过工厂)并对任何调用者(如服务层类)隐藏这些连接。
http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject。 html
您认为将其保留在外部有什么优点吗?
I think you've answered your own question. The basic design pattern explains the DAO should be creating/retrieving the Connection (say via a Factory) and hide those from any callers like Service tier classes.
http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html
Do you see any merits in keeping this external?
从纯粹的可用性和标准的角度来看,我认为您希望 DAO 负责连接。这毕竟是数据访问的一个主要功能。
考虑您的使用情况,您是否希望使用 DAO 的表示/业务层代码充分了解数据库以创建传递到 DAO 的连接?如果您需要移动数据库或重新命名它怎么办,此时封装连接非常好。
在我看来,使用管理自己连接的 DAO 还可以更简洁地使用调用代码中的对象,从而提高整体可读性。
Coming at this from a pure usability and standards viewpoint I think that you want the DAO to take care of the connections. That is after all a main function of Data access.
Consider your use, would you want the presentation/business layer code that uses the DAO to know enough about the database to create a connection to pass to the DAO? What if you need to move the database or re-name it, at that point its very nice to have the connections encapsulated.
Using a DAO that manages its own connections also makes for a more terse use of the objects in the calling code, boosting the overall readability, IMO.
我认为 DAO 的关键点在于您可以在应用程序的其余部分不知道或关心的情况下更换实现。我实际上已经在一个项目中做到了这一点。 DAO 接口保持不变,但连接详细信息发生变化,因此您无法使其在外部可见。
I think the key point of a DAO is that you can swap out the implementation without the rest of the application knowing or caring. I've actually done this on a project. The DAO interface remains the same but connection details change so you CAN'T have it visible externally.