每个“容器”类一个DAO或每个表一个DAO?

时间:2021-02-15 21:02:22

I have a 'container' class with fields that are contained in several database tables, and I use the DAO pattern for accessing the data.

我有一个'容器'类,其中的字段包含在几个数据库表中,我使用DAO模式来访问数据。

The question is, should I create a single DAO for this 'container' class, or is it better to have one DAO per table and combine their data?

问题是,我应该为这个“容器”类创建一个DAO,还是每个表有一个DAO并合并它们的数据更好?

1 个解决方案

#1


11  

You should design your DAO according to your application needs, not the layout of your database. Start of with one DAO, and if it becomes too large, then refactor it into multiple DAOs in a way that makes sense to your code.

您应该根据应用程序需求设计DAO,而不是数据库的布局。从一个DAO开始,如果它变得太大,那么以一种对你的代码有意义的方式将它重构为多个DAO。

The whole point of a DAO is to hide any database concepts (like tables) from your application. Your application should just view it as a service with some useful methods.

DAO的重点是隐藏应用程序中的任何数据库概念(如表)。您的应用程序应该只使用一些有用的方法将其视为服务。

For example, if your application needs some user data that comes from both the Users table and the EmailAddresses table, your application code should not have to coordinate two DAOs - it should call one DAO method getUserDetails() and the DAO will hide the fact that multiple tables need to be called.

例如,如果您的应用程序需要来自Users表和EmailAddresses表的一些用户数据,那么您的应用程序代码不应该协调两个DAO - 它应该调用一个DAO方法getUserDetails(),并且DAO将隐藏这样的事实:需要调用多个表。

I am recommending the first of the options in your question, but I wouldn't restrict yourself to the rule "one DAO per container class".

我建议您提出问题中的第一个选项,但我不会将自己局限于“每个容器类一个DAO”这一规则。

#1


11  

You should design your DAO according to your application needs, not the layout of your database. Start of with one DAO, and if it becomes too large, then refactor it into multiple DAOs in a way that makes sense to your code.

您应该根据应用程序需求设计DAO,而不是数据库的布局。从一个DAO开始,如果它变得太大,那么以一种对你的代码有意义的方式将它重构为多个DAO。

The whole point of a DAO is to hide any database concepts (like tables) from your application. Your application should just view it as a service with some useful methods.

DAO的重点是隐藏应用程序中的任何数据库概念(如表)。您的应用程序应该只使用一些有用的方法将其视为服务。

For example, if your application needs some user data that comes from both the Users table and the EmailAddresses table, your application code should not have to coordinate two DAOs - it should call one DAO method getUserDetails() and the DAO will hide the fact that multiple tables need to be called.

例如,如果您的应用程序需要来自Users表和EmailAddresses表的一些用户数据,那么您的应用程序代码不应该协调两个DAO - 它应该调用一个DAO方法getUserDetails(),并且DAO将隐藏这样的事实:需要调用多个表。

I am recommending the first of the options in your question, but I wouldn't restrict yourself to the rule "one DAO per container class".

我建议您提出问题中的第一个选项,但我不会将自己局限于“每个容器类一个DAO”这一规则。