DAO 与 ORM(休眠)模式

发布于 2024-09-29 01:15:17 字数 1432 浏览 3 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

弥枳 2024-10-06 01:15:17

ORM 和 DAO 是正交的概念。一个与对象如何映射到数据库表有关,另一个是用于编写访问数据的对象的设计模式。你不能在它们之间进行选择。您可以拥有 ORM 和 DAO 是同一个应用程序,就像您不需要 ORM 来使用 DAO 模式一样。

也就是说,虽然您从来没有真正需要任何东西,但您应该使用 DAO。该模式适合模块化代码。您将所有持久性逻辑保留在一个地方(关注点分离,对抗抽象泄漏)。您允许自己与应用程序的其余部分分开测试数据访问。并且您允许自己测试与数据访问隔离的应用程序的其余部分(即您可以模拟您的 DAO)。

另外,遵循 DAO 模式很容易,即使实现数据访问可能很困难。因此,您花费很少(或没有),但收获却很多。

编辑--
对于您的示例,您的登录方法应该位于某种 AuthenticationService 中。您可以在那里处理异常(在登录方法中)。如果您使用 Spring,它可以为您管理很多事情:(1) 事务,(2) 依赖项注入。您不需要编写自己的事务或 dao 工厂,您只需围绕服务方法定义事务边界,并将 DAO 实现定义为 bean,然后将它们连接到您的服务中。

EDIT2

使用该模式的主要原因是分离关注点。这意味着所有持久性代码都位于一处。这样做的副作用是可测试性和可维护性,而且这使得以后更容易切换实现。如果您正在构建基于 Hibernate 的 DAO,那么您绝对可以操纵 DAO 中的会话,这就是您应该做的。反模式是与持久性相关的代码发生在持久层之外(泄漏抽象法则)。

交易有点棘手。乍一看,事务似乎与持久性有关,而且确实如此。但它们不仅仅是持久性的问题。事务也是您的服务关注的一个问题,因为您的服务方法应该定义一个“工作单元”,这意味着服务方法中发生的所有事情都应该是原子的。如果您使用 Hibernate 事务,那么您将必须在 DAO 之外编写 Hibernate 事务代码,以定义使用许多 DAO 方法的服务周围的事务边界。

但请注意,事务可以独立于您的实现——无论您是否使用 hibernate,您都需要事务。另请注意,您不需要使用 hibernate 事务机制——您可以使用基于容器的事务、JTA 事务等。

毫无疑问,如果您不使用 Spring 或类似的东西,事务将会很痛苦。我强烈建议使用 Spring 来管理您的事务,或者使用 EJB 规范,我相信您可以使用注释定义围绕服务的事务。

查看以下链接,了解基于容器的交易。

容器管理的事务

会话和事务

我从中得到的信息是,您可以轻松地在服务级别定义 DAO 之外的事务,并且不需要编写任何事务代码。

另一种(不太优雅的)替代方案是将所有原子工作单元放入 DAO 中。您可以使用 CRUD DAO 来执行简单的操作,然后使用更复杂的 DAO 来执行多个 CRUD 操作。这样,您的程序化事务保留在 DAO 中,您的服务将调用更复杂的 DAO,而不必担心事务。

以下链接是 DAO 模式如何帮助您简化代码的一个很好的示例

AO 与 ORM (hibernate) 模式

(thanx @daff

注意接口的定义如何使其适合您的业务逻辑只关心 UserDao 的行为。它不关心实施。您可以使用 hibernate 或仅使用 JDBC 编写 DAO。因此,您可以更改数据访问实现,而不会影响程序的其余部分。

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.

That said, while you never really need anything, 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).

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.

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.

EDIT2

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).

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.

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.

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 believe you can define transactions around your services with annotations.

Check out the following links, for container based transactions.

Container-Managed Transactions

Sessions And 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.

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.

The following link is a good example of how the DAO pattern can help you simplify code

AO vs ORM(hibernate) pattern

(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.

蹲墙角沉默 2024-10-06 01:15:17

让我为 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
    }
}

因此,正如已经提到的,DAO 是一种最小化耦合的设计模式
在你的应用程序和你的后端之间,而 ORM 处理如何
将对象映射到对象关系数据库(这减少了之间的耦合)
数据库和应用程序,但最终没有使用 DAO
你的应用程序将取决于所使用的 ORM 或更高级别
JPA 等标准)。

因此,如果没有 DAO,就很难更改您的应用程序(例如,迁移到 NoSQL 数据库而不是兼容 JPA 的 ORM)。

Let me provide a source code example to hvgotcodes good answer:

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).

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).

鱼忆七猫命九 2024-10-06 01:15:17

不,我认为这是不正确的。 ORM是实现DAO的一种方式;你可以选择做DAO而不做ORM。

你已经倒过来了:我认为 ORM 比 DAO 更重,因为依赖性更大。我可以直接用 JDBC 编写 DAO,无需 ORM。 IMO,那更轻。

我们是否同意取决于我们如何定义“轻”和“重”。我将按照依赖关系进行分析——除了 JDK 本身之外,还需要额外的 JAR 数量。

No, I don't think that's correct. ORM is one way to implement DAO; you can choose to do DAO without ORM.

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.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文