每个“容器"类一个 DAO 还是每个表一个 DAO?
我有一个容器"类,其字段包含在多个数据库表中,并且我使用 DAO 模式来访问数据.
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,还是每个表都有一个 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 开始,如果它变得太大,则以对您的代码有意义的方式将其重构为多个 DAO.
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 的全部意义在于隐藏应用程序中的任何数据库概念(如表).您的应用程序应该将其视为具有一些有用方法的服务.
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.
例如,如果您的应用程序需要一些来自 Users 表和 EmailAddresses 表的用户数据,您的应用程序代码不应该协调两个 DAO - 它应该调用一个 DAO 方法 getUserDetails() 并且 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.
我推荐您问题中的第一个选项,但我不会将自己限制在每个容器类一个 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".
相关文章