DAO 模式的最佳实践? [英] Best practice for DAO pattern?

查看:31
本文介绍了DAO 模式的最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过很多代码使用了service-dao模式,不知道这种模式的由来.它强制前层调用 service ,然后将部分 service 任务委托给 dao.

I've seen a lot of codes use a service-dao pattern , I don't know the origin of this pattern . It force the front layer call service , then delegates some of the service task to dao.

我想问:

  1. DAO 层是否仅执行与数据访问相关的任务?异常封装之类的东西呢?
  2. 有没有其他模式可以用来代替这个或比这个更好?
  3. 我认为 pojo 域模型和事务脚本使简单的问题变得复杂,是否有可能完全消除 dao 层?

推荐答案

理想情况下,您的 DAO 层抽象化"了对某些数据存储系统(数据库、文件系统、LDAP 目录等)的访问.因此,从这个意义上说,它仅用于与数据访问相关的任务.但是,您也可以有一个 DAO 层来访问 Web 服务或应用程序外部的一些其他组件.这是关键点,它提供了对某些外部组件的访问.

Ideally, your DAO layer 'abstracts away' the access to some data storage system (database, file system, LDAP directory, ...). So in that sense it is used only for data access related tasks. However, you could also have a DAO layer that accesses a web service or some other component external to your application. That's the key point, it provides access to some external component.

主要思想是您的 DAO 层没有实现细节可以逃逸到更高层(隔离).考虑这个问题的一个很好的起点是:如果我计划替换我的 DAO 层提供访问权限的组件(例如数据库),我需要做什么?例如,您在 XML 文件中有一些数据,并且您计划将数据迁移到数据库.

The main idea is that there are no implementation details of your DAO layer that escape to higher layers (isolation). A good starting point for thinking about this is: what would I need to do if I plan to replace the component (a database for example) that my DAO layer provides access to? For example, you have some data inside XML files and you plan to migrate the data to a database.

假设您有各种与 XML 相关的异常逃逸到您的 DAO 层.然后将您的 XML 层迁移到数据库层变得非常困难.但是,如果您已经封装了 DAO 层的所有实现细节,这将变得容易得多.

Suppose you have all kinds of XML-related exceptions that escape your DAO layer. Then it becomes quite hard to migrate your XML layer to a database layer. However, if you've encapsulated all implementation details of your DAO layer, this will become a lot easier.

归根结底,这与代码的可维护性有关.您对特定层(服务、DAO 等)的实现细节的依赖越少,您的代码的可维护性就越好.

In the end, it's about maintainability of your code. The less dependencies you have on implementation details of a specific layer (services, DAO, ...), the better maintainable your code is.

这篇关于DAO 模式的最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆