有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java关于DAOs的正确使用

DAO是否仅为基本CRUD操作保留,或者它还可能包含一些复杂的搜索逻辑

想象一下Book和Author这两个实体类以及它们之间的多对多关系。此时,一个DAO就足够了,因为两个实体的基本CRUD操作是相同的

然而,随着应用程序变得越来越复杂,出现了新的需求,例如: 1.为给定作者查找第一本书 2.查找作者在一段时间内所写的书籍 3.查找特定作者所写的关于特定主题的书籍 4.等

这些都应该去哪里?我现在是否为每个实体创建一个单独的DAO类,并将它们放在那里?它们是否属于DAO层

我面临着这样的困境: 以下方法应用于何处: findBooks(作者) findBooks(出版商) 都在书道里,还是一个在作者道里,另一个在出版道里

或者我应该考虑一个全新的抽象,它位于DAO之上,并将它们留给基本的CRUD操作——例如一个SearchService,它列出了所有可能的搜索


共 (3) 个答案

  1. # 1 楼答案

    这些都应该去哪里?我现在是否为每个实体创建一个单独的DAO类,并将它们放在那里?它们到底属于道层吗

    see below.

    我有一个难题:以下方法应该去哪里:findBooks(Author-Author)findBooks(Publisher-Publisher)在BookDAO中,或者一个在AuthorDAO中,另一个在Publisher-dao中

    It depends and i think it's not a question of enterprise software architecture, instead, OOD. As your logic is getting complicated, you must keep in mind to increase cohesion and reduce coupling between software compontents, and respectively extract a new class (Extact Class from Refactoring Catalog http://martinfowler.com/refactoring/catalog/extractClass.html) with these methods which is considered to be belong to the same business context, like AuthorDAO for all methods about Author functionality and Books for all Books calls, so on to make your code more readable, reusable, testable, maintable, ...

    或者我应该考虑一个全新的抽象概念,它位于DAO之上,并将它们留给基本的CRUD操作——例如一个SearchService,它列出了所有可能的搜索

    That abstraction exists in multitier model, is called business layer, if you mean business logic. You can associate your business logic with business objects. But the findXXX methods belong to your DAO which lies between persistence and business layer.

  2. # 2 楼答案

    Is DAO only reserved for the basic CRUD operations

    不。请随意将所有数据访问逻辑放在DAOs中

    不要把DAODAL混淆起来:

  3. # 3 楼答案

    Where should all these go? Do I create now a separate DAO class for each entity, and put them there? Do they belong to the DAO layer at all?

    肯定是DAO(层)的工作和要求。你所拥有的一切都无关紧要。具体的方法应该去它所属的道

    Or maybe I should think of a completely new abstraction, which is on top of DAOs and leaves them to basic CRUD ops - for example a SearchService, which lists all possible searches?

    这里有两件事

    1. 看起来您正在使用Hibernate或某种ORM工具。所以我相信你有正确的目标。您可以在DAO层中使用这些对象,而不是地图、列表或原语,而不会产生任何问题。无论如何,不偏离DAO层,您仍然可以在这里使用DAO层。并根据需要验证业务规则
    2. 看起来你指的是AbstractDAO模式(搜索/谷歌也一样),Hibernate和Spring也提供了类似的功能。Spring也为此提供了一种SearchService工具(实际上是类)