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
I suppose that the pattern "DAO class per entity" is absolutely redundant for an ORM-managed data layer. Instead, the DAO layer should be composed of a set of one-fits-all CRUD method set that operate on arbitrary entity classes and a large number of methods that perform more sophisticated operations on data. If the functionality is large enough then the DAO layer should be split into multiple classes based on the domain criteria, what makes the approach more similar to the Service-Oriented Architecture.
The purpose of all this introduction to layers was to make maintainability easy and simple.
The purpose of the 1st Layer (Data Access Layer) is to deal with the database logic and prevent the Business Layer from knowing any of the DB details.
The Data Access Layer uses POJO or EJBs (DAO) to implement IoC and POJOEJBs uses Hibernate or ORM mapping to actually deal with the Database Layer.
So, if you want your business logic should not care about which, what & how a database is being used, accessed and updated and you want DAO to take care of this
DAO can support the logic of changing different tables to support operation by making a number of hibernate calls.
In essence, you are implementing a layered approach in Data Access Layer by breaking its functionality again in two layers aka DAO and Hibernate.
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<Book> 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.
It depends what your layer's goals are. You put an abstraction in to supply a different set of semantics over another set. Generally further layers are there to simplify somethings such as development of future maintennance. But they could have other uses.
For example a DAO (or persistence handling) layer over an ORM code supply specialised recovery and error handling functionality that you didn't want polluting the business logic.