Monday, February 20, 2012

Generic DAO/Service layer - Spring 3 and JPA 2.0

I've found a couple of very good articles with a simple code samples and clear explanations. They both talk about service/DAO layer organization.

To be more precise, the first one is about Generic DAO pattern that I personally prefer (but it could be just as well applied on the service layer).

1) Generic DAO pattern in Java with Spring 3 and JPA 2.0 (Code Project article by Madalin Ilie)

And the second one explains the difference between DAO and service layer, and where and how do we make the cut between them.

2) Layered architecture with Hibernate and Spring 3 (Carlos Vara's blog post)

A small addition on my side would be a sample of Madalin's Generic DAO pattern applied on DAO classes provided by Carlos + using JPA instead of Hibernate:

public class GenericDaoImpl<T> implements GenericDao<T> {

 private Class<T> type;
 EntityManager em;

 public void setEntityManager(EntityManager em) {
  this.em = em;

 public GenericDaoImpl() {
  Type t = getClass().getGenericSuperclass();
  ParameterizedType pt = (ParameterizedType) t;
  this.type = (Class) pt.getActualTypeArguments()[0];

 public T findById(String id) {
  return em.find(type, id);
 public T save(T entity) {
  if (((BaseEntity)entity).getId() != null) {
   entity = em.merge(entity); // update
  } else {
   em.persist(entity); // insert
  return entity;


1 comment: