Mittwoch, 5. Oktober 2011

Generic DAO and JPA

Generic DAO is a design pattern to reduce and prevent code replacing on basic CRUD operations. Hibernate-Generic-DAO (http://code.google.com/p/hibernate-generic-dao/) provides exactly this pattern solution for Hibernate or JPA.

UML Overview of this example:

BaseDAO is an extension of GenericDAO and it must be extended by each DAO class of the project.

JPAGenericDAO is a generic, abstract class to be extended by each concrete DAO class.

Sample code:
  1. /**
  2.  * @author Hasan Oezdemir
  3.  * @since 01.10.2011
  4.  *
  5.  */
  6. public abstract class JPAGenericDAO<T, ID extends Serializable> extends GenericDAOImpl<T, ID> implements
  7.         BaseDAO<T, ID> {
  8.     private static final Logger logger = LoggerFactory.getLogger(JPAGenericDAO.class);
  9.    
  10.     @PersistenceContext(unitName="scheduling")
  11.     private EntityManager entityManager;
  12.    
  13.     public JPAGenericDAO(){
  14.         super();
  15.     }
  16.    
  17.     @PostConstruct
  18.     public void initialized(){
  19.         logger.info( "initializing generic dao, setting entity manager: {}", entityManager);
  20.         this.setEntityManager(entityManager);
  21.         JPASearchProcessor searchProcessor = new JPASearchProcessor(new JPAAnnotationMetadataUtil());
  22.         this.setSearchProcessor(searchProcessor);
  23.     }
  24.     @Override
  25.     public T findByExampleUnique(T example) {
  26.         Search s = this.createSearch(example);
  27.         return searchUnique(s);
  28.     }
  29.     @Override
  30.     public Collection<T> findByExample(T example) {
  31.         Search s = this.createSearch(example);
  32.         return search(s);
  33.     }
  34.    
  35.     protected Search createSearch(T example) {
  36.         Search s = new Search(example.getClass());
  37.         s.addFilter(this._getFilterFromExample(example));
  38.         return s;
  39.     }
  40. }

UserDAO extends the BaseDAO :

  1. /**
  2.  * @author Hasan Oezdemir
  3.  * @since 01.10.2011
  4.  *
  5.  */
  6. public interface UserDAO extends BaseDAO<User, Long> {
  7. }


and a sample reference implementation of DAOs :

  1. /**
  2.  * @author Hasan Oezdemir
  3.  * @since 01.10.2011
  4.  *
  5.  */
  6. @Singleton
  7. public class JPAUserDAO extends JPAGenericDAO<User, Long> implements UserDAO {
  8.     public JPAUserDAO(){
  9.         super();
  10.     }
  11. }


We keep basic CRUD operations in our abstract class but we have also seperate interfaces to provide 'Model' specific method and keep them seperate from generic DAO solutions.

Keine Kommentare:

Kommentar veröffentlichen