在 Spring MVC 和 Hibernate 中使用通用 DAO 和通用服务模式的优缺点是什么

What is the pros and cons of using Generic DAO and Generic Service Pattern in Spring MVC with Hibernate

我想在我的新项目中实现 Generic DAO 和 Generic Service。我在网上看到了很多例子。

在开始之前我想知道使用这种设计模式的优缺点。

谁能告诉我使用这种模式是否明智?

当多个 DAO 类 想要与数据库通信时,通用 DAO 设计模式就出现了(根据示例 CRUD(创建、读取、更新和删除)),如果没有这种设计模式,您将最终编写单独的代码来为每个 DAO 类 进行数据库调用(使用会话),这通常是一项乏味的工作,因为对于 DAO 类 的每个新实现,您都必须编写自己的代码来处理数据库。

以下是使用 Generic DAO 的一些优点和缺点。

注意: 下面给出的详细信息是我从对 SO 问题 Pros and Cons of the use of DAO pattern

的回答中学到的

Pros

1. Creates a nice abstraction layer of the actual storage system.

2. Provide a more object-oriented view of the persistence layer .

3. Provide a clean separation between the domain class and code which will perform the data access from databse.[using JDBC,ORM[like hibernate] or JPA]

4. Once you have the general CRUD flow set, the same layout can be repeated for other DAOs.

Cons

1. If you handwrite the DAOs, then the code can become tedious and repetitive you have to use code generators/templates and ORM.

问 - 谁能告诉我使用这种模式是否明智?

A- 在观察了上述优缺点之后,我在我的应用程序中使用了 Generic DAO 作为抽象层,以 CRUD 方式与数据库进行通信,这实际上帮助我减少了很多重复代码做同样的事情其他 DAOs.At 首先需要时间来适应它,之后使用 Generic DAO 会让你的生活变得轻松。

我认为,对 DAO 和通用 DAO 有不同的看法会更好。关于优点的一些话(如果你使用 ORM,我的建议是有效的,例如 Hibernate,而不是简单的 JDBC)。

  1. Creates a nice abstraction layer of the actual storage system.

这是营销废话。在现实生活中,我们在各种 RDBMS(Oracle RDBMS -> PostgreSQL)之间迁移时遇到了问题。不谈存储系统类型的变化(例如 RDBMS -> NoSQL)。

  1. Provide a more object-oriented view of the persistence layer.

没有!很难做好。大多数 DAO 实现都有许多方法,例如

getSomething(String x, String y, String z);
getSomethingOther(String x, String z); 
  1. Provide a clean separation between the domain class and code which will perform the data access from databse.[using JDBC,ORM[like hibernate] or JPA].

可能是,但这种分离的用处被夸大了。

  1. Once you have the general CRUD flow set, the same layout can be repeated for other DAOs.

正确。