The Generic DAO pattern in Java with Spring 3 and JPA 2.0

One thing that annoys me the most is code duplication. The DAO layer is the perfect candidate for this kind of situation. Often, developers forget about OOP, polymorphism and design patterns and just copy&paste code, change the name of the class and voila, we have a brand “new” BankDao class. I’ll present you how to implement a generic DAO pattern to avoid code duplication and preserve type safety in the same time. Why would you care about type safety and just don’t go use the EntityManager’s generic methods. Well, for various reasons:

  1. You know for sure which entity objects can be persisted
  2. You avoid a lot of explicit casts which are error prone
  3. The code is cleaner and  very easy to follow
  4.  You actually apply OOP principles like inheritance and polymorphism. ;)

The purpose of this article is not to get you familiar with the DAO pattern, but to show you a better way of using it. You can find a complete reference about DAO here: DataAccessobject.

The Generic DAO interface

Let’s get started. First of all this article assumes you are using Spring 3 (although this can be easily adapted to Spring 2.5) and JPA 2.0 in you project and the initial configuration is in place:  you already have a data sources declared, an entity manager factory, etc.  The application is basically up&running.

The foundation of using a Generic DAO is the CRUD operations that you can perform on each entity. And this is the least you can have. Additional generic methods can be defined like: count all objects of a specific type; execute generic queries based on some parameters, etc. You’ll see a sample bellow for countAll().

The core of this pattern will be an interface called, surprisingly, GenericDao and its implementation Continue reading