问题描述
数据访问对象 (DAO) 是一种常见的设计模式,由 Sun 推荐.但是最早的 Java DAO 示例直接与关系数据库交互——它们本质上是在执行对象关系映射 (ORM).现在,我在 JDO 和 Hibernate 等成熟的 ORM 框架之上看到 DAO,我想知道这是否真的是个好主意.
Data Access Objects (DAOs) are a common design pattern, and recommended by Sun. But the earliest examples of Java DAOs interacted directly with relational databases -- they were, in essence, doing object-relational mapping (ORM). Nowadays, I see DAOs on top of mature ORM frameworks like JDO and Hibernate, and I wonder if that is really a good idea.
我正在开发一个使用 JDO 作为持久层的 Web 服务,正在考虑是否引入 DAO.我预见在处理包含其他对象映射的特定类时会出现问题:
I am developing a web service using JDO as the persistence layer, and am considering whether or not to introduce DAOs. I foresee a problem when dealing with a particular class which contains a map of other objects:
public class Book {
// Book description in various languages, indexed by ISO language codes
private Map<String,BookDescription> descriptions;
}
JDO 足够聪明,可以将其映射到BOOKS"和BOOKDESCRIPTIONS"表之间的外键约束.它透明地加载 BookDescription 对象(我相信使用延迟加载),并在持久化 Book 对象时持久化它们.
JDO is clever enough to map this to a foreign key constraint between the "BOOKS" and "BOOKDESCRIPTIONS" tables. It transparently loads the BookDescription objects (using lazy loading, I believe), and persists them when the Book object is persisted.
如果要引入一个数据访问层",写一个BookDao这样的类,把所有的JDO代码都封装在里面,那么这个JDO对子对象的透明加载不就绕过了数据访问层吗?为了一致性,难道所有的 BookDescription 对象不应该通过一些 BookDescriptionDao 对象(或 BookDao.loadDescription 方法)加载和持久化吗?然而,以这种方式重构会使操作模型变得不必要地复杂.
If I was to introduce a "data access layer" and write a class like BookDao, and encapsulate all the JDO code within this, then wouldn't this JDO's transparent loading of the child objects be circumventing the data access layer? For consistency, shouldn't all the BookDescription objects be loaded and persisted via some BookDescriptionDao object (or BookDao.loadDescription method)? Yet refactoring in that way would make manipulating the model needlessly complicated.
所以我的问题是,直接在业务层调用 JDO(或 Hibernate,或您喜欢的任何 ORM)有什么问题?它的语法已经非常简洁,并且与数据存储无关.将其封装在数据访问对象中有何优势(如果有)?
So my question is, what's wrong with calling JDO (or Hibernate, or whatever ORM you fancy) directly in the business layer? Its syntax is already quite concise, and it is datastore-agnostic. What is the advantage, if any, of encapsulating it in Data Access Objects?
推荐答案
这取决于你的层的目标是什么.您放入一个抽象以提供一组与另一组不同的语义.通常,还有更多层可以简化诸如未来维护的开发之类的事情.但它们可以有其他用途.
It depends what your layer's goals are. You put an abstraction in to supply a different set of semantics over another set. Generally further layers are there to simplify somethings such as development of future maintennance. But they could have other uses.
例如,ORM 代码上的 DAO(或持久性处理)层提供专门的恢复和错误处理功能,您不想污染业务逻辑.
For example a DAO (or persistence handling) layer over an ORM code supply specialised recovery and error handling functionality that you didn't want polluting the business logic.
这篇关于为什么将 DAO 层放在持久层之上(如 JDO 或 Hibernate)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!