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
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.