Why put a DAO layer over a persistence layer (like JDO or Hibernate)

前端 未结 10 929
梦谈多话
梦谈多话 2021-01-31 09:13

Data Access Objects (DAOs) are a common design pattern, and recommended by Sun. But the earliest examples of Java DAOs interacted directly with relational databases -- they were

10条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-31 09:38

    When using an ORM tool like JDO or JPA, DAOs are an anti-pattern. In this case, creating a "data access layer" is completely unnecessary and will only add extra code and complexity to the codebase, making it harder to develop and maintain.

    Based on my previous experience, I would recommend the use of a simple static facade, say Persistence, to provide an easy to use, high-level API for persistence-related operations.

    Then, you can use an static import to get easy access to those methods anywhere they are useful. For example, you could have code like the following:

    
        List cheapBooks = 
            find("select b from Book where b.price < ?", lowPriceForBooks);
        ...
        Book b = new Book(...);
        persist(b);
        ...
        Book existingBook = load(Book.class, bookId);
        remove(existingBook);
        ...
    

    The code above is as easy and simple as possible, and can be easily unit tested.

提交回复
热议问题