Java DAO vs ORM(休眠)模式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4037251/
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
DAO vs ORM(hibernate) pattern
提问by blow
i read in some articles DAO is not mandatory with hibernate and its implementation is by "it depends", in other words, we can choose between ORM vs DAO pattern.
我在一些文章中读到 DAO 对于 Hibernate 不是强制性的,它的实现是“取决于”,换句话说,我们可以在 ORM 与 DAO 模式之间进行选择。
Ok, let's assume that i don't want use a DAO pattern, so im using only session CRUD and query operation provided by hibernate(my ORM).
好的,让我们假设我不想使用 DAO 模式,所以我只使用了 hibernate(我的 ORM)提供的会话 CRUD 和查询操作。
Especially for the "search" and "find" queries is not correct to rewrite them always, so is reasonable think to put them into a class.
特别是对于“搜索”和“查找”查询,总是重写它们是不正确的,因此将它们放在一个类中是合理的。
But then this class is a simple DAO without all implementation of DAO pattern and DAOFactory, only a lightweight implementation of a DAO. So, the point is that we need alway a DAO and the choice is heavy DAO implementation vs lightweight DAO implementation?
但是这个类是一个简单的 DAO,没有 DAO 模式和 DAOFactory 的所有实现,只是一个 DAO 的轻量级实现。所以,关键是我们总是需要一个 DAO 并且选择是重 DAO 实现还是轻量级 DAO 实现?
What i said is wrong?
我说的有错吗?
EDITAnother problem i have is where put dao interactions, for example i have to login an User and write a Log of the login (useless example i know...)
编辑我的另一个问题是在哪里放置 dao 交互,例如我必须登录一个用户并编写登录日志(我知道无用的例子......)
So in a DAO pattern i have all generic dao implementations, a DAOFactory and finally UserHibernateDAO and LogHibernateDAO. The login operation is a business method:
所以在 DAO 模式中,我有所有通用的 dao 实现,一个 DAOFactory,最后是 UserHibernateDAO 和 LogHibernateDAO。登录操作是一种业务方法:
private void login(String username, String password){
daoFactory.beginTransaction();
UserDAO userDao=daoFactory.HIBERNATE.getUserDao();
LogDAO logDao=daoFactory.HIBERNATE.getLogDao();
if(userDao.checkAccount(username, password){
User user=userDao.findByAccount(username, password);
logDao.save(new Log("log-in", user);
}
daoFactory.commit();
}
Is this reasonable? Can i use dao in this way? If i want handle exception, the better place to do it is ina a business logic?
这合理吗?我可以这样使用 dao 吗?如果我想处理异常,最好的地方是在业务逻辑中?
EDIT2Let's assume to use a DAO pattern, the main reason to do it is to be able to switch between tecnhology(ORM->JDBC etc..), it all fine and ok, BUT where can i handle hibernate session and transaction? I can't put it into a DAO, it's anty pattern, and i can't put it into a service layer, becouse in a hipohtetycal switch i have to remove all this transaction(becouse other tecnhology may not use them).
EDIT2让我们假设使用 DAO 模式,这样做的主要原因是能够在技术(ORM->JDBC 等)之间切换,一切都很好,但是我在哪里可以处理休眠会话和事务?我不能把它放到一个 DAO 中,它是反模式,我不能把它放到服务层,因为在一个 hipohtetycal 交换机中我必须删除所有这些事务(因为其他技术可能不会使用它们)。
采纳答案by hvgotcodes
ORM and DAO are orthogonal concepts. One has to do with how objects are mapped to database tables, the other is a design pattern for writing objects that access data. You don't choose 'between' them. You can have ORM and DAO is the same application, just as you don't need ORM to use the DAO pattern.
ORM 和 DAO 是正交的概念。一个与对象如何映射到数据库表有关,另一个是用于编写访问数据的对象的设计模式。你不会在它们之间做出选择。你可以让 ORM 和 DAO 是同一个应用程序,就像你不需要 ORM 来使用 DAO 模式一样。
That said, while you never really needanything, you should use DAOs. The pattern lends itself to modularized code. You keep all your persistence logic in one place (separation of concerns, fight leaky abstractions). You allow yourself to test data access separately from the rest of the application. And you allow yourself to test the rest of the application isolated from data access (i.e. you can mock your DAOs).
也就是说,虽然你从来不需要任何东西,但你应该使用 DAO。该模式适用于模块化代码。您将所有持久性逻辑都放在一个地方(关注点分离,与泄漏抽象作斗争)。您允许自己与应用程序的其余部分分开测试数据访问。并且您允许自己测试与数据访问隔离的应用程序的其余部分(即您可以模拟您的 DAO)。
Plus, following the DAO pattern is easy, even if implementing data access can be difficult. So it costs you very little (or nothing) and you gain a lot.
此外,遵循 DAO 模式很容易,即使实现数据访问可能很困难。所以它花费你很少(或没有),而你获得了很多。
EDIT --With respect to your example, your login method should be in some sort of AuthenticationService. You can handle exceptions there (in the login method). If you used Spring, it could manage a bunch of things for you: (1) transactions, (2) dependency injection. You would not need to write your own transactions or dao factories, you could just define transaction boundaries around your service methods, and define your DAO implementations as beans and then wire them into your service.
编辑 -关于您的示例,您的登录方法应该在某种 AuthenticationService 中。您可以在那里处理异常(在 login 方法中)。如果您使用 Spring,它可以为您管理很多事情:(1) 事务,(2) 依赖注入。您不需要编写自己的事务或 dao 工厂,您只需围绕服务方法定义事务边界,并将 DAO 实现定义为 bean,然后将它们连接到您的服务中。
EDIT2
编辑2
The main reason to use the pattern is to separate concerns. That means that all your persistence code is in one place. A side effect of this is, test-ability and maintainability, and the fact that this makes it easier to switch implementations later. If you are building Hibernate based DAOs, you can absolutely manipulate the session in the DAO, that is what you are supposed to do. The anti pattern is when persistence related code happens outside of the persistence layer (law of leaky abstractions).
使用该模式的主要原因是分离关注点。这意味着您所有的持久性代码都在一个地方。这样做的副作用是可测试性和可维护性,并且这使得以后更容易切换实现。如果您正在构建基于 Hibernate 的 DAO,您绝对可以在 DAO 中操作会话,这就是您应该做的。反模式是当与持久性相关的代码发生在持久层之外时(泄漏抽象定律)。
Transactions are a bit trickier. At first glance, transactions might seem to be a concern of persistence, and they are. But they are not only a concern of persistence. Transactions are also a concern of your services, in that your service methods should define a 'unit of work', which means, everything that happens in a service method should be atomic. If you use hibernate transactions, then you are going to have to write hibernate transaction code outside of your DAOs, to define transaction boundaries around services that use many DAO methods.
交易有点棘手。乍一看,事务似乎是一个持久性问题,而且确实如此。但它们不仅仅是对持久性的关注。事务也是您的服务关注的问题,因为您的服务方法应该定义一个“工作单元”,这意味着在服务方法中发生的一切都应该是原子的。如果您使用休眠事务,那么您将不得不在 DAO 之外编写休眠事务代码,以围绕使用许多 DAO 方法的服务定义事务边界。
But note that the transactions can be independent of your implementation -- you need transactions whether or not you use hibernate. Also note that you don't need to use the hibernate transaction machinery -- you can use container based transactions, JTA transactions, etc.
但请注意,事务可以独立于您的实现——无论您是否使用休眠,您都需要事务。另请注意,您不需要使用休眠事务机制——您可以使用基于容器的事务、JTA 事务等。
No doubt that if you don't use Spring or something similar, transactions are going to be a pain. I highly recommend using Spring to manage your transactions, or the EJB spec where I believeyou can define transactions around your services with annotations.
毫无疑问,如果您不使用 Spring 或类似的东西,事务将会很痛苦。我强烈建议使用 Spring 来管理您的事务,或者使用 EJB 规范,我相信您可以使用注释围绕您的服务定义事务。
Check out the following links, for container based transactions.
查看以下链接,了解基于容器的交易。
Container-Managed Transactions
What I am gathering from this is that you can easily define the transactions outside the DAOs at the service level, and you don't need to write any transaction code.
我从中收集到的是,您可以轻松地在服务级别定义 DAO 之外的事务,并且您不需要编写任何事务代码。
Another (less elegant) alternative is to put all atomic units of work within DAOs. You could have CRUD DAOs for the simple operations, and then more complicated DAOs that do more than one CRUD operations. This way, your programmatic transactions stay in the DAO, and your services would call the more complicated DAOs, and wouldn't have to worry about the transactions.
另一种(不太优雅的)替代方案是将所有原子工作单元放在 DAO 中。您可以拥有用于简单操作的 CRUD DAO,然后是执行多个 CRUD 操作的更复杂的 DAO。这样,您的程序化事务就留在 DAO 中,您的服务将调用更复杂的 DAO,而不必担心事务。
The following link is a good example of how the DAO pattern can help you simplify code
以下链接很好地说明了 DAO 模式如何帮助您简化代码
(thanx @daff)
Notice how the definition of the interface makes it so that you business logic only cares about the behavior of the UserDao. It doesn't care about the implementation. You could write a DAO using hibernate, or just JDBC. So you can change your data access implementation without affecting the rest of your program.
请注意接口的定义如何使您的业务逻辑只关心 UserDao 的行为。它不关心实现。您可以使用 hibernate 或仅使用 JDBC 编写 DAO。因此,您可以更改数据访问实现,而不会影响程序的其余部分。
回答by duffymo
No, I don't think that's correct. ORM is one way to implement DAO; you can choose to do DAO without ORM.
不,我不认为那是正确的。ORM 是实现 DAO 的一种方式;你可以选择在没有 ORM 的情况下做 DAO。
You've got it backwards: I'd consider ORM to be heavier than DAO, because the dependencies are greater. I can write a DAO in straight JDBC without ORM. That's lighter, IMO.
你已经倒退了:我认为 ORM 比 DAO 重,因为依赖关系更大。我可以在没有 ORM 的直接 JDBC 中编写 DAO。这更轻,国际海事组织。
Whether or not we agree depends on how we define "light" and "heavy". I'm going by dependencies - the number of extra JARs required over above the JDK itself.
我们是否同意取决于我们如何定义“轻”和“重”。我将通过依赖项 - JDK 本身之上所需的额外 JAR 的数量。
回答by Daff
Let me provide a source code example to hvgotcodes good answer:
让我提供一个源代码示例给 hvgotcodes 很好的答案:
public class Application
{
private UserDao userDao;
public Application(UserDao dao)
{
// Get the actual implementation
// e.g. through dependency injection
this.userDao = dao;
}
public void login()
{
// No matter from where
User = userDao.findByUsername("Dummy");
}
}
public interface UserDao
{
User findByUsername(String name);
}
public class HibernateUserDao implements UserDao
{
public User findByUsername(String name)
{
// Do some Hibernate specific stuff
this.session.createQuery...
}
}
public class SqlUserDao implements UserDao
{
public User findByUsername(String name)
{
String query = "SELECT * FROM users WHERE name = '" + name + "'";
// Execute SQL query and do mapping to the object
}
}
public class LdapUserDao implements UserDao
{
public User findByUsername(String name)
{
// Get this from LDAP directory
}
}
public class NoSqlUserDao implements UserDao
{
public User findByUsername(String name)
{
// Do something with e.g. couchdb
ViewResults resultAdHoc = db.adhoc("function (doc) { if (doc.name=='" + name + "') { return doc; }}");
// Map the result document to user
}
}
So, as already mentioned, DAO is a design pattern to minimize coupling between your application and you backend whereas ORM deals with how to map objects into an object-relational database (which reduces coupling between the database and you application, but in the end, without using a DAO your application would be dependend on the ORM used or on a higher level a standard like JPA).
因此,正如已经提到的,DAO 是一种设计模式,可以最大限度地减少应用程序和后端之间的耦合,而 ORM 则处理如何将对象映射到对象关系数据库(这减少了数据库和应用程序之间的耦合,但最终,如果不使用 DAO,您的应用程序将依赖于所使用的 ORM 或更高级别的标准(如 JPA)。
Therefore, without DAOs, it would be really hard to change your application (e.g. moving to a NoSQL database instead of a JPA compatible ORM).
因此,如果没有 DAO,将很难更改您的应用程序(例如,移动到 NoSQL 数据库而不是 JPA 兼容的 ORM)。