JPA implementation patterns: Data Access Objects

Vincent Partington

The JPA, short for Java Persistence API, is part of the Java EE 5 specification and has been implemented by Hibernate, TopLink, EclipseLink, OpenJPA, and a number of other object-relational mapping (ORM) frameworks. Because JPA was originally designed as part of the EJB 3.0 specification, you can use it within an EJB 3.0 application. But it works equally well outside of EJB 3.0, for example in a Spring application. And when even Gavin King, the designer of Hibernate, recommends using JPA in the second edition of Hibernate in Action, a.k.a. Java Persistence with Hibernate, it's obvious that JPA is here to stay.

Once you get over your fear of annotations ;-), you find that there is plenty of literature out there that explains the objects and methods within the API, the way these objects work together and how you can expect them to be implemented. And when you stick to hello-world-style programs, it all seems pretty straight forward. But when you start writing your first real application, you find that things are not so simple. The abstraction provided by JPA is pretty leaky and has ramifications for larger parts of your application than just your Data Access Objects (DAO's) and your domain objects. You need to make decisions on how to handle transactions, lazy loading, detached object (think web frameworks), inheritance, and more. And it turns out that the books and the articles don't really help you here.

At least, that is what I discovered when I really started using JPA for the first time. In the coming weeks, I would like to discuss the choices I came up against and the decisions I made and why I made them. When I'm done, we'll have a number of what I would like to not-too-modestly call JPA implementation patterns. ;-)

Do we really need a DAO?

So, let's start with the thing you would probably write first in your JPA application: the data access object (DAO). An interesting point to tackle before we even start is whether you even need a DAO when using JPA. The conclusion of that discussion more than a year ago was "It depends" and while it is very hard to argue with such a conclusion :-), I would like to stick with the idea that a DAO does have its place in a JPA application. Arguably it provides only a thin layer on top of JPA, but more importantly making a DAO per entity type gives you these advantages:

  • Instead of having to pick the right EntityManager method every time you want to store or load data, you decide which one to use once and you and your whole team can easily stick to that choice.
  • You can disallow certain operations for certain entity types. For example, you might never want your code to remove log entries. When using DAO's, you just do not add a remove method to your LogEntry DAO.
  • Theoretically, by using DAO's you could switch to another persistence system (like plain JDBC or iBATIS). But because JPA is such a leaky abstraction I think that that is not realistically possible for even a slightly complex application. You do get a single point of entry where you can add tracing features or keep performance statistics.
  • You can centralize all the queries on a certain entity type instead of scattering them through your code. You could use named queries to keep the queries with the entity type, but you'd still need some central place where the right parameters are set. Putting both the query, the code that sets the parameters, and the cast to the correct return type in the DAO seems a simpler thing to do. For example:
    public List findExecutingChangePlans() {
          Query query = entityManager.createQuery(
                "SELECT plan FROM ChangePlan plan where plan.state = 'EXECUTING'");
          return (List) query.getResultList();
    }

So when you decide you are going to use DAO's, how do you go about writing them? The highlighted (in bold) comment in the Javadoc for Spring's JpaTemplate seems to suggest that there's not much point in using that particular class, which also makes JpaDaoSupport superfluous. Instead you can write your JPA DAO as a POJO using the @PersistenceContext annotation to get an EntityManager reference. It will work in an EJB 3.0 container and it will work in Spring 2.0 and up if you add the PersistenceAnnotationBeanPostProcessor bean to your Spring context.

The type-safe generic DAO pattern

Because each DAO shares a lot of functionality with the other DAO's, it makes sense to have a base class with the shared functionality and then subclass from that for each specific DAO. There are a lot of blogs out there about such a type-safe generic DAO pattern and you can even download some code from Google Code. When we combine elements from all these sources, we get the following JPA implementation pattern for DAO's.

The entity class

Let's say we want to persist the following Order class:

@Entity
@Table(name = "ORDERS")
public class Order {
	@Id
	@GeneratedValue
	private int id;
	private String customerName;
	private Date date;

	public int getId() { return id; }
	public void setId(int id) { this.id = id; }

	public String getCustomerName() { return customerName; }
	public void setCustomerName(String customerName) { this.customerName = customerName; }

	public Date getDate() { return date; }
	public void setDate(Date date) { this.date = date;}
}

Don't worry too much about the details of this class. We will revisit the specifics in other JPA implementation patterns. The @Table annotation is there because ORDER is a reserved keyword in SQL.

The DAO interfaces

First we define a generic DAO interface with the methods we'd like all DAO's to share:

public interface Dao {
      void persist(E entity);
      void remove(E entity);
      E findById(K id);
}

The first type parameter, K, is the type to use as the key and the second type parameter, E, is the type of the entity. Next to the basic persist, remove, and findById methods, you might also like to add a List findAll() method. But like the entity class itself, we will revisit the DAO methods in later JPA implementation patterns.

Then we define one subinterface for each entity type we want to persist, adding any entity specific methods we want. For example, if we'd like to be able to query all orders that have been added since a certain date, we can add such a method:

public interface OrderDao extends Dao {
	List findOrdersSubmittedSince(Date date);
}

The base DAO implementation

The third step is to create a base JPA DAO implementation. It will have basic implementation of all the methods in the standard Dao interface we created in step 1:

public abstract class JpaDao implements Dao {
	protected Class entityClass;

	@PersistenceContext
	protected EntityManager entityManager;

	public JpaDao() {
		ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
		this.entityClass = (Class) genericSuperclass.getActualTypeArguments()[1];
	}

	public void persist(E entity) { entityManager.persist(entity); }

	public void remove(E entity) { entityManager.remove(entity); }

	public E findById(K id) { return entityManager.find(entityClass, id); }
}

Most of the implementation is pretty straight forward. Some points to note though:

  • The constructor of the JpaDao includes the method proposed by my colleague Arjan Blokzijl to use reflection to get the entity class.
  • The @PersistenceContext annotation causes the EJB 3.0 container or Spring to inject the entity manager.
  • The entityManager and entityClass fields are protected so that subclasses, i.e. specific DAO implementations, can access them.

The specific DAO implementation

And finally we create such a specific DAO implementation. It extends the basic JPA DAO class and implements the specific DAO interface:

public class JpaOrderDao extends JpaDao implements OrderDao {
	public List findOrdersSubmittedSince(Date date) {
		Query q = entityManager.createQuery(
			"SELECT e FROM " + entityClass.getName() + " e WHERE date >= :date_since");
		q.setParameter("date_since", date);
		return (List) q.getResultList();
	}
}

Using the DAO

How you get a reference to an instance of your OrderDao depends upon whether we use EJB 3.0 or Spring. In EJB 3.0 we'd use a annotation like this:

@EJB(name="orderDao")
private OrderDao orderDao;

while in Spring we can use the XML bean files or we can use autowiring like this:

@Autowired
public OrderDao orderDao;

In any case, once we have a reference to the DAO we can use it like this:

Order o = new Order();
o.setCustomerName("Peter Johnson");
o.setDate(new Date());
orderDao.persist(o);

But we can also use the entity specific query we added to the OrderDao interface:

List orders = orderDao.findOrdersSubmittedSince(date);
for (Order each : orders) {
	System.out.println("order id = " + each.getId());
}

With this type-safe DAO pattern we get the following advantages:

  • No direct dependency on the JPA api from client code.
  • Type-safety through the use of generics. Any casts that still need to be done are handled in the DAO implementation.
  • One logical place to group all entity-specific JPA code.
  • One location to add transaction markers, debugging, profiling, etc. Although as we will see later, we will need to add transaction markers in other parts of our applications too.
  • One class to test when testing the database access code. We will revisit this subject in a later JPA implementation pattern.

I hope this convinces you that you do need DAO's with JPA. :-)

And that wraps up the first JPA implementation pattern. In the next blog of this series we will build on this example to discuss the next pattern. In the meantime I would love to hear from you how you write your DAO's!

For a list of all the JPA implementation pattern blogs, please refer to the JPA implementation patterns wrap-up or browse all the posts in this category.

Comments (59)

  1. Andrew Phillips - Reply

    March 9, 2009 at 7:04 pm

    If you're working with Spring, you might also consider annotating your Repository (DAO) implementations with @Repository.
    This enables (if you want it) exception translation and, as per 2.5, allows the DAOs to be auto-detected via component scanning.

    http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/stereotype/Repository.html

  2. Lars - Reply

    March 9, 2009 at 10:14 pm

    Hi Vincent,

    I still use the SessionFactory for my DAO implementations because JPA still does not have a good counterpart for Criteria IMHO.

    Lars

  3. Gregg Bolinger - Reply

    March 10, 2009 at 12:33 am

    I wrote an article about this exact thing April of last year and then recently doing the same thing with iBatis.

    http://www.greggbolinger.com/blog/2008/04/17/1208457000000.html

    http://www.greggbolinger.com/blog/2009/02/25/1235585940000.html

  4. Sander Mak - Reply

    March 10, 2009 at 12:24 pm

    The reflection trick is nice, I just implement a concrete getDomainClass() method in each concrete subclass.

    The Hades Dao framework by the way does more or less the same thing (and more), http://trac.synyx.org/hades

  5. Wesslan - Reply

    March 10, 2009 at 1:58 pm

    Crank is a very good implementation of a "Generic DAO" in JPA: http://code.google.com/p/krank/

  6. Mario Gleichmann - Reply

    March 10, 2009 at 4:17 pm

    Good Post!

    For myself, i summarized some of the reasons why you still should stick with DAOs or at least being aware of some consequences if not, under

    http://gleichmann.wordpress.com/2007/11/22/why-dao-wont-die/

    and

    http://gleichmann.wordpress.com/2009/02/17/dao-its-not-about-layering-its-about-abstraction/

    Greetings

    Mario

  7. Dave - Reply

    March 10, 2009 at 4:52 pm

    For your generic DAO implementation, should you not use the generic type in your perist/remove method parameter declarations? That is, should it not be declared as "public void persist(E entity)" instead of "public void persist(Object entity)"?

  8. Erik Rozendaal - Reply

    March 10, 2009 at 4:56 pm

    Having the entity specific DAOs extend a generic interface may not always be the best idea. For example, your generic interface may have a delete method but your Customer entity may not support deletion.

    See http://codebetter.com/blogs/gregyoung/archive/2009/01/16/ddd-the-generic-repository.aspx for more discussion on this.

  9. Vincent Partington - Reply

    March 10, 2009 at 5:15 pm

    @Dave: you are absolutely right. This was probably caused by Eclipse code completion being clever or something. :-) I changed the following two methods in JpaDao.

    From:

    	public void persist(Object entity) { entityManager.persist(entity); }
    	public void remove(Object entity) { entityManager.remove(entity); }
    

    To:

    	public void persist(E entity) { entityManager.persist(entity); }
    	public void remove(E entity) { entityManager.remove(entity); }
    

    Thx for spotting that!

    Regards, Vincent.

  10. Viraf Karai - Reply

    March 12, 2009 at 8:18 pm

    Excellent post and a great use of generics. I believe that this pattern can be easily extended to other persistence engines such as Hibernate and iBatis.

    Erik Rozendaal does bring up a good point though about drawbacks from extending generic interfaces. However, your example should cover the vast majority of implementations.

  11. Vincent Partington - Reply

    March 13, 2009 at 3:42 pm

    @Gregg: The generic type-safe DAO pattern seems pretty wide spread. That's why I was disappointed that the otherwise excellent Java Persistence with Hibernate book didn't mention it. Or any of the other things I'll be mentioning the coming weeks.

    @Mario: Nice to hear more reasons (both practical and theoretical) why DAO's do make sense.

    @Erik: While the blog you refer to makes an interesting point it does seem a tad on the strict side. Extending on the idea that a Repository is like a collection that would mean that generic collection API's are a bad thing too. Or is that the idea? ;-)

  12. Jose Javier García - Reply

    March 14, 2009 at 10:48 am

    Very good post, thanks for sharing.

  13. intesar - Reply

    March 15, 2009 at 2:46 am

    I'm a open source developer and using this pattern since one year, this was first presented by IBM in early 07. However i use this pattern little differently i mark GenericDaoImpl as abstract so it should be directly injected or used.

  14. Lars - Reply

    March 15, 2009 at 2:17 pm

    As promised :-)

    I think before we can say if DAO's make sense we need to know the rest of the application architecture.
    Do you expose your DAO interface directly to clients (e.g. the web layer)? If so it probably makes sense you use DAO's.
    On the other hand: if you are the only one using your own DAO's (and you expose your data only via Services that then use DAO's) then it does not make sense and just adds needless complexity.

    But on the other other hand; since you use the limited EntityManager instead of the superior SessionFactory with its Criteria you probably do need a DAO to make code intention revealing:

    Query q = entityManager.createQuery("SELECT e FROM "
    + entityClass.getName() + " e WHERE date >= :date_since");
    q.setParameter("date_since", date);
    return (List) q.getResultList()
    

    Using Criteria makes it already intention revealing:

    return (List) session.createCriteria(Order.class).add(Restrictions.ge("data_since", date)).list();
    

    So summarised: It depends on the bigger picture before you can really say if a DAO makes sense or not.

  15. Alex Snaps - Reply

    March 24, 2009 at 3:49 pm

    The

    this.entityClass = (Class) genericSuperclass.getActualTypeArguments()[1];
    

    could throw a classcastexception in case the class is itself generified, this should solve this:

    Type type = genericSuperClass.getActualTypeArguments()[1]
    if (type instanceof ParameterizedType) {
      this.entityClass = (Class) ((ParameterizedType) type).getRawType();
    } else {
      this.entityClass = (Class) type;
    }
    

    To be completely correct, I think you should also resolve the EntityName explicitly, as it might not use the default, which is the unqualified named of the entity class itself...

  16. Vincent Partington - Reply

    March 26, 2009 at 5:52 pm

    @intesar: good point. In fact that is what I also do in practice. I just forgot to make the JpaDao class abstract in this example. I've now updated the blog to reflect this.

  17. Vincent Partington - Reply

    March 26, 2009 at 5:58 pm

    @Lars: I'm not sure that using Criteria makes the code intention revealing. But I guess that depends on how much you're into the Criteria API. ;-) You'll be glad to know that JPA 2.0 will also have a Criteria API.

  18. Nick Parfene - Reply

    April 12, 2009 at 10:38 am

    Great stuff Vincent.

    Only one problem though: if you look at the class diagram of your example you will find that the you can navigate to the generic Dao interface in two ways: either via the JpaDao abstract class or via the OrderDao interface. Here is a copy of the class declaration:

    public class JpaOrderDao extends JpaDao implements OrderDao

    Basically both JpaDao and OrderDao implement the same Dao interface which is a bit "ugly".

    Now this can also come in handy if the JpaOrderDao is defined as a Stateless Session bean since the OrderDao interface could become the local EJB interface that is used to lookup the EJB.

    My question to you is: if you were to create a Stateless session bean to expose this Entity would you reuse the JpaOrderDao (e.g. annotate it @Stateless) or would you create a new "facade" EJB that would in turn delegate to this Dao implementation.

    Cheers, Nick

  19. Vincent Partington - Reply

    April 19, 2009 at 3:50 pm

    @Nick: The interface inheritance is the one I think is important here. It is the one that allows the DAO to be proxied, mocked, etc. It is the interface I would expose as a stateless session bean.

    The class (implementation) inheritance is just there as a simple way to reuse the implementation. You could get the same effect using delegation instead of inheritance. I guess this is my old-school OO upbringing shining through. ;-)

  20. rod - Reply

    May 25, 2009 at 9:31 pm

    I personnally use an even more generic approach (perhaps I should initiate a blog to describe it in detail): I use one single "PersistenceService" implementation that is generic for all entities that all inherit from the same basic class (Persistable). The drawback is that specific queries are not isolated in DAOs, but need to be written inside the business services (and call queryObject or queryObjects methods). Which can be chocking for some "purists".

    @Entity
    @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
    public class Persistable {
    	Long id;
    	Long version;
    	@Id
    	@GeneratedValue(strategy = GenerationType.TABLE)
    	public Long getId() {
    		return id;
    	}

    ...

    public interface PersistenceService {
        public  <T> save(T persistable) throws Exception;
        public  <T> update(T persistable) throws Exception;
        public  <T> find(Class clazz, long id);
        public  List findAll(Class entityClass);
        public  void delete(T persistable) throws Exception;
        public  <T> queryObject(String query);
        public  List queryObjects(String query);
        public  long count(Class entityClass);
    }
    @Transactional(propagation=Propagation.REQUIRED)
    public class PersistenceServiceImpl implements PersistenceService {
        @PersistenceContext
        private EntityManager em;
        public  <T> save(T persistable) throws Exception
        { 
            em.persist(persistable);
            return persistable;
        }
        public  <T> update(T persistable) throws Exception
        {
            persistable = em.merge(persistable);
            return persistable;
        }
        public  <T> find(Class clazz, long id)
        {
            return em.find(clazz, id);
        }
        public  <T> queryObject(String query)
        {
            return (T) em.createQuery(query).getSingleResult();
        }
        public  List queryObjects(String query)
        {
            return em.createQuery(query).getResultList();
        }

    ...

  21. rod - Reply

    May 25, 2009 at 9:36 pm

    oops, some "" have been eaten by html
    The PersistenceService methos signatures all use generics like this:
    "public T save(T persistable) throws Exception;"
    instead of
    "public T save(T persistable) throws Exception;"

  22. rod - Reply

    May 25, 2009 at 9:38 pm

    '' (superior) where eaten again !!!

  23. Vincent Partington - Reply

    May 27, 2009 at 9:12 am

    @Rod: I've put the <'s back in. I hope I put them all in the right place. ;-)

  24. Vincent Partington - Reply

    June 13, 2009 at 11:49 am

    @Rod: Interesting approach. While it is more generic than the entity-specific DAO approach, it does indeed have the disadvantage of not containing the entity-specific queries. Your approach also does not allow for certain DAO's to not have certain methods (for example no delete on a LogRecord entityi).

    It does provide a type-safe wrapper around the EntityManager interface, which helps in itself. But leaves the entity specific features to the service methods.

    I guess it's all a matter of where you want to put certain responsibilities. But isn't that always the case. ;-)

  25. rod - Reply

    June 22, 2009 at 4:02 pm

    I totally agree with your points.
    To de-activate delete on certain DAOs, I use a complementary pattern: all the methods of this generic persistence service (as well as all other generic services of my framework), implement the "observer" pattern. They "raise" a pre/post function event that can be "observed" to: either perform checks (on pre-store for exemple) or perform post treatments. This is a very generic approach to customize the behaviour of a generic service without changing it.
    Inline with your previous remarks, you'll probably argue that the observer needs to check the type of the source object and you will be right ;o)

  26. Vincent Partington - Reply

    June 22, 2009 at 7:57 pm

    @Rod: That's an interesting approach. Have you considered using a decorator pattern or AOP for that pre/post processing? It does sound nicer than the @Pre/@Post lifecycle hooks that JPA provides because those tend to pollute your entities. Then again they are guaranteed to be called at the right moment by the JPA provider.

  27. rod - Reply

    June 27, 2009 at 6:37 pm

    I've never been a fan of AOP approach for one main reason: it allows anyone to change the behaviour of existing code without any "contract". I think it is important that a law layer of an application (or a framework) clearly indicates (in a contract) what are the extension points that it provides. That's why I prefer raising events explicitly and observing these events to customize the behaviour of the low level layer of of the framework.
    I could also have used standard JPA pre/post hooks, but as I said, I wanted to extend this concept to other generic services.

  28. Stefan - Reply

    July 2, 2009 at 11:07 pm

    So the OrderDao is a SLSB? I cannot get this to work, my understanding is that DI only works for beans, not for pojos?

  29. Vincent Partington - Reply

    July 5, 2009 at 1:51 pm

    @Stefan: In EJB 3.0 the DAO would indeed be an SLSB. I've only used this pattern within the Spring Framework but this approach should also work in EJB 3.0. You would need to annotate the DAO interface (OrderDao in this example) with the @Remote annotation and the implementation (JpaOrderDao) with the @Stateless annotation.

    The OpenEJB documentation has a nice example of setting up a stateless EJB.

  30. Rodrigo - Reply

    July 15, 2009 at 8:20 pm

    @The original post

    I don't even call DAO a pattern. With with ORM, DAO became an anti-pattern to me.

    JPA (or Hibernate, my choice) is a DAL (data access layer), and putting a data access layer on top of another data access layer is nonsense.

    Nevertheless, I do consider an Adapter on top of the Hibernate Session is a great improvement, that addresses your first concern. My adapter does even more than just disallow certain operations, but also I aggregate quite a few very interesting data-retrieving methods that can be used to any entity in the system, only by using some Criteria and some reflection (recursive findByExample and findByNaturalId, for example).

    The second argument of the article seems to me too little to gain with too much drawbacks. I would need to have 400 classes, and maybe other 400 interfaces just in order to disallow one remove() method in one entity? I'd rather block it with an Interceptor. Well, maybe this also only exists for Hibernate?

    In regards to the third argument, I don't think I understood it. Is it a reason for using DAO's, or a reason for not using them? I can see that without a DAO we do have a single entry point.

    Last, I don't have a problem with many queries. In my last system, with 15000 lines of Java code (jsps excluded), we have 20 queries. I just put all of them in one class of constants. Very clean, no query in the services. If there were many more queries, I could consider a few more class of constants, but they would never be as many as one 10th of the amount of entities.

    Anyway, with my approach, I guarantee that the application is not directly dependent on the API; everything is type safe (my adapter used generics);
    any entity specific code is in the entity; the services are the places for the transaction marking, and there are not as many services as there are entities.

    The advantages for not using DAOs:
    - I have only one class to test, since every DAO should need tests, since you decided to put entity specific code in each of them.
    - when I'm executing an operation inserting several entities, I don't need to use several DAOs. Hibernate cascades all the inclusions. If that's done in an DAO environment, the the "guarantees" that you tried to centralize in the the DAOs fall apart.
    - the same can happen to updating entities. I will collect entities from the repository, and I can just update the data in them, and and in this case I don't even need to call any update(). So, any restrictions to updating the entities, or any additional behavior could by bypassed if they are in a DAO.

  31. [...] Data Access Objects [...]

  32. Aurelio Calegari - Reply

    July 16, 2009 at 1:40 pm

    Hi,

    I see here some Java EE architectural gaffes here:

    Do not make a DAO a Session Bean and do Not encapsulate a Domain Store in a DAO. It's a misuse of both patterns... Please refer in full to http://www.amazon.co.uk/Core-J2EE-Patterns-Practices-Strategies/dp/0131422464/ref=sr_1_2?ie=UTF8&s=books&qid=1247669640&sr=1-2

    EJBs are pooled in the container, so let's say we'll have 30 instances in the pool for every single dao. If you have hundreds or nearly thousands of tables in big systems you've got your system to create those pools for each DAO type at deploy time and you'll be waisting important server resources. You might also run out of memory as the container eagerly create the session beans instances... A DAO should be a POJO that's used on demand and is garbage collected on demand too...

    You're limitating how much you're system will access its own data by making them EJBs. It's not to be in the lowest level. It should be in the perspective of your system you give to the client (no matter if it's the web tier, a web service or whatever). In that you have a way to control and narrow how much concurrent access we'll be allowing through that door.

    What's more, by making DAOs a EJB you're encouraging EJB chaining that can be equally evil for huge systems with great user mass. So if you system is small today with a few hundreds of users that's fine, but it will be doomed when it goes for massive thousands. Even if you input more hourse power, we'll have to go for a manageable nightmare of finetunning the container EJBs instances individually.

    Originally the DAO pattern, as it says in the J2EE Core Catalog is to hide the complexity and the specifics of native calls to legacy systems shilding thus the client from having to deal with native code. From that we have many strategies such as DAO factories that bring same functionality for different platforms, etc.

    JPA is an implementation of the J2EE Core Pattern called Domain Store, which does pretty much of what DAO does. It hides from you the native and specifics of a legacy system, so you DON'T NEED to shield the client for that. That's nonsense to shield access to a Domain Store in a DAO.

    Also I would say that this specific logic you put in the dao, could be well placed in the J2EE Core Pattern called Application Service, where you could place the logic to handle that entity and incorportate the business rules behind that.

    Note that it also SHOULD NOT BE AN EJB. After EJB 3.0 many people are overusing EJBs and building bad system that will not scale and will create a number of bottle necks because of the amount of EJBs in Biz and Integeration tier all tied and chained together. EJB is cool, but not to be overused this way...

    Hope the people read the catalog and use the J2EE platform correctly... Guys, don't forget to read the original anti-patterns for EJB:

    • Bitter EJB: http://www.amazon.co.uk/Bitter-EJB-Bruce-Tate/dp/1930110952/ref=sr_1_1?ie=UTF8&s=books&qid=1247669429&sr=8-1; and
    • J2EE Anti-Patterns: http://www.amazon.co.uk/J2EE-Antipatterns-Bill-Dudney/dp/0471146153/ref=sr_1_1?ie=UTF8&s=books&qid=1247669538&sr=1-1

    EJB has came live again as sun facilitated its usage, but today people who start adopting EJBs keep making the same mistakes people were doing in 2001...

    Regards

    Aurelio

  33. Carlos - Reply

    July 17, 2009 at 9:37 pm

    My understanding is that the DAO idea is to have a layer that hides all the complexity of the data access hiding the specifics and giving the chance to change implementation of that data access in the future without changing the rest of the application (as long as we keep the interface).

    JPA gives the chance to navigate across the object tree freely (using the relations one-to-many, many-to-one, etc), wich is a great feature I think.

    If we return a JPA Entity in the DAO interfaces, we are putting in the DAO interface contract the ability to navigate the returned object.

    If we later change the DAO implementation in the future for something different from JPA, we should keep the ability to navigate the returned object, wich could be very difficult depending on the new decided implementation of the DAO.

    This, among with the previously expossed regarding that JPA is already hidding data access implementation, give me the idea that creating another extra layer like DAO, could be not very convenient (more classes, more layers that only does a object pass through).

    Regards

    Carlos

  34. Vincent Partington - Reply

    July 19, 2009 at 3:05 pm

    @Rodrigo: What does your Adapter on top of Hibernate look like? I'm interested to see it and compare it to this DAO approach. As I understand it now, it tries to achieve the same things as this DAO pattern. But I guess it does so in a different manner.

  35. Vincent Partington - Reply

    July 19, 2009 at 3:10 pm

    @Aurelio Calegari: You make a good point why the DAO should not be an EJB. As I've said above I've only used this pattern within Spring. My assumption that it would/should be an SLSB in EJB 3.0 is not correct. As for whether the pattern described above is a DAO or an "Application Service"; I guess I chose this name because it is one most people understand.

  36. Vincent Partington - Reply

    July 19, 2009 at 3:13 pm

    @Carlos: The reason I use this DAO pattern is to prevent business logic from having to directly use the JPA API, which is especially cumbersome when writing queries. Switching to a different persistence mechanism is not a scenario I envision, so the full capabilities of JPA are exposed, such as being able to navigate the object graph. If that means that this pattern should be called something other than DAO, well, please see my comment above. ;-)

  37. Nicolas Le Coz - Reply

    July 27, 2009 at 10:44 am

    Hello Vincent,

    Thanks for your articles.

    I have one question, during my project we have realize DAOs like this :

    public class myDaoImpl implements myDao {
        …
        public void save(Entity e) {
            if (e.getId() == null) {
                entityManager.persist(e);
            }
            else {
                entityManager.merge(e);
            }
        }
        …
    }
    

    But after several mistakes on lazy loading we transform on (we add return e):

    public class monDaoImpl implements monDao {
        …
        public monEntity save(monEntity e) {
            if (e.getId() == null) {
                entityManager.persist(e);
            }
            else {
                entityManager.merge(e);
            }
        }
        return e ;
    }
    

    We add "return e", because it seems that Hibernate changes the reference of entity, even if the JPA method signature is "void persist(Object o)" but the other sign "Object merge(Object o)". After call of persist Hibernate changes the reference of entity to a proxy to manage entity that is monitored by Hibernate". So, outside the method "save" we lost reference of Hibernate proxy on entity, and we must to reattach then entity to Hibernate session.

    you confirm it? Is it a specificity of Hibernate and not JPA?

    Nicolas Le Coz (Xebia FR)

  38. Vincent Partington - Reply

    July 27, 2009 at 5:26 pm

    @Nicolas Le Coz: The JPA spec says that EntityManager.merge will return a reference to another object than the one passed in when the object was already loaded in the current context. So that explains why a would sometime change. But to really make it work you would have to capture the result of the merge method like so:

    public class monDaoImpl implements monDao {
        …
        public monEntity save(monEntity e) {
            if (e.getId() == null) {
                entityManager.persist(e);
            }
            else {
                e = entityManager.merge(e);
            }
        }
        return e ;
    }
    

    For more details on this please read the blog on saving (detached) entities.

  39. [...] Cet article est une proposition de traduction de l’article de Vicent Patington : Do we really need DAO ? [...]

  40. Twitted by bubbl - Reply

    August 4, 2009 at 10:19 am

    [...] This post was Twitted by bubbl [...]

  41. alex - Reply

    August 19, 2009 at 9:42 am

    I'm trying jpa with hibernate as provider and @EJB(name="xxx") annotation cannot be resolved.
    How can I solve this problem ?
    Thank you.

  42. Vincent Partington - Reply

    August 24, 2009 at 7:17 pm

    @alex: The JPA specification, the one supported by Hibernate, is a subset of the EJB 3.0 specification that only deals with persistence. The @EJB annotation is part of the EJB 3.0 specification and not of the JPA subset and as such is not supported by Hibernate.

  43. Simon Massey - Reply

    September 24, 2009 at 3:47 pm

    I am with @Rodrigo that the word DAO is not an orm term it is too heavily associated with the failures of EJB2 where folk just wrote their own JDBC result set mapper loading DTOs. In that universe as mentioned by @Aurelio you hide the DAO from the clients of your services - it is at the bottom of the stack. That pattern has been around for a decade and a huge set of systems still work that way so it has "trademark ownership" of that word. (Now I am starting to feel real old taking about the "bad old days".)

    If we look at Chris Richardson's (pre-JPA) book POJOs In Action he too wants to have an abstraction for grouping queries or optional eager loads. He calls them "Repositories". He actually has sample code which demonstrates swapping between JDO and Hibernate implementations. Clearly with JPA we don't really need the swap out capabilities. The book explains who the iBatis framework can be used with an alternative set of true DAO/DTO patters to do some high performance search screens without having to pollute your use of ORM by forcing it to "play DTO mapper".

    Where the difference really stands out between what is an old school DAO and how we might want to do things with JPA is the following: with the Chris Richardson approach he names the Repository classes to be part of his domain model that you expose to the client / façades. That is certainly not what you do with an old school DAO from the EJB2 world which was usually deemed to be strictly in the data layer and never to be touched except via a service (as @Carlos says). JPA however makes it respectable to get closer to your persistence store than it was to get close to JDBC, Oracle jPub (shudder), or some-home-brew-dto-mapper. That is one of the point that @Aurelio makes.

    Saying that the Repository (aka your JPA DOA) is part of the Domain Model makes sense when we consider that the abstraction is mainly there to encapsulate how findByThisAndThat(...) methods actually set the named parameters of a named query. Any façade which wants to intact with record data structure exposed entities would want to call such finders to obtain things which it would then work with (via services) then perhaps call further loadThat/findOther methods on the Repository (aka your DOA) required to update the presentation view.

    I wrote a demo app (for an AJAX framework) and copied the GenericJpaDao that I found on the Loom project. They kindly pointed out that they had upgraded their framework to use an ExtendedEntityManager:

    http://loom.svn.sourceforge.net/viewvc/loom/loom/trunk/src/java/org/loom/persistence/ExtendedEntityManagerOperations.java?revision=1682&view=markup

    Although I have not tried that I think that looks like it is in alignment with what the Chris Richardson book was documenting pre-JPA in terms of being the respectable "Domain Store" which @Aurelio makes reference to which can be exposed to your façades as part of your Domain Model. Of course it is just a re-labelling of the generic DAO but as the Clean Code book says labels are important (thanks for your post about that book I bought it based on your mention of it).

  44. tbee - Reply

    January 26, 2010 at 3:11 pm

    It is interesting to see how everyone seems to only have the word "web" between their ears when talking about persistence / JPA. I currently have a business model that is used both in a web (SOAP) context and a swing application. So I have no use for @PersistenceContext, because my EMs in the swing application are bound to the JFrames, but the same BM must also run in a webalike context, where the EM's are bound to requests.

    I decided to go for a "EntityManagerFinder", which can be configured to bind either way. And because I do not use @PersistenceContext there is no need for me to have DAO instances where this annotation can be set. The method DAO can become statics and then you can get rid of the DAO interface as well. And since they're now just static methods, it's much more convenient to move them into the entity class.

    Order.findById(...)
    Order.findAll()
    etc

  45. JPA Implementation Patterns | Upthrust - Reply

    January 30, 2010 at 12:34 pm

    [...] Data Access Objects [...]

  46. Rodrigo - Reply

    November 25, 2010 at 10:12 pm

    Hello,
    Nice post and comments. I would like to ask your opinion about some unclear points I still face.
    Why these DAOs have to have those interfaces if they are implemented only once, like OrderDao, OrderDaoImpl. AFAIK Interfaces are meant for polymorphism, and often these objects are very specific and their are used in a composite/injected manner, so I see no point for these interfaces. Wouldn't we achieve the same if the GenericDAO was an abstract class with generic behavior and was extended in case we need some specific entity logic?
    Do you think the approaches that are discussed here are still valid for JEE6 and CDI?
    Thinking about the JEE6, and trying not to overuse or underuse patterns, what would be an good way to organize the architecture for a small web application nowadays?

    Thanks a lot,

    []'s

    Rodrigo

  47. Vincent Partington - Reply

    December 10, 2010 at 9:30 pm

    @Rodrigo: You are right indeed that the interfaces are not necessary for the pattern. But by programming to interfaces you get a few nice added benefits:

    • They allow you to swap in different implementation, e.g. for testing.
    • They allow the simple java dynamic proxy approach to aspects used by Spring to enable transactions. Then again, Spring can also use CGlib to do the same for classes without interfaces. And for JEE6 this really is not necessary.

    So while they are not strictly necessary for the DAO pattern, I think it is good form to program to interfaces. But in the end, it's up to you.

  48. chintan - Reply

    April 7, 2011 at 11:52 pm

    While using above code, i am getting entityManager as null. i don't understand why?

  49. Josepma - Reply

    April 10, 2011 at 6:32 pm

    Hello and thanks for that very interesting post. There is just somwthing that I do not understand:

    Shouldn't the Dao interface be a generic one? That is, shouldn't it be written like this:

    public interface Dao {
          void persist(E entity);
          void remove(E entity);
          E findById(K id);
    }
    

    ????

  50. Josepma - Reply

    April 10, 2011 at 6:32 pm

    Hello and thanks for that very interesting post. There is just somwthing that I do not understand:

    Shouldn't the Dao interface be a generic one? That is, shouldn't it be written like this:

    public interface Dao {
          void persist(E entity);
          void remove(E entity);
          E findById(K id);
    }
    

    ????

    Thank you very much....

    Josepma

  51. Josepma - Reply

    April 10, 2011 at 6:37 pm

    Sorry for my last post. It showed exactly my problem: my browser eats and I got confused. But looking at the page source, it got clear.

    Thanks anyway.
    Josepma

  52. [...] and Spring. I really like the approaches exposed in the articles DDD: The Generic Repository and JPA implementation patterns: Data Access Objects. My aim is to build the perfect Repository in Domain-Driven Design with JPA and [...]

  53. [...] and Spring. I really like the approaches exposed in the articles DDD: The Generic Repository and JPA implementation patterns: Data Access Objects. My aim is to build the perfect Repository in Domain-Driven Design with JPA and [...]

  54. Alexander - Reply

    November 5, 2011 at 8:16 pm

    Many thanks for the article! It's still actual. I have implemented generic DAO in scala language with your help:

    protected val entityClass = getClass().getGenericSuperclass().asInstanceOf[ParameterizedType]
    .getActualTypeArguments().first.asInstanceOf[Class[T]]

    The other stuff is trivial...

  55. SunKing2 - Reply

    February 4, 2012 at 9:34 pm

    Thanks for your insight. Though a long-time java developer, I'm just getting started in JPA and Java EE for enterprise development; I have a large hill to climb.

  56. dplaton - Reply

    February 7, 2012 at 5:17 pm

    Hello there,

    What if we want to use this generic DAO in a CRUD service (yes, CRUD operations suck but someone needs to do it)? We could inject 10 XxxxxDao objects there (one for each entity type) , but this would defeat the purpose...

  57. [...] A typical design strategy for this is to use Data Access Object (DAOs). With this pattern you bundle all the data access methods relating to a single Entity into a DAO, encapsulating all your queries within this class, making them easier to test and maintain. Typically these DAOs all end up looking very similar, with every DAO providing the same basic CRUD operations. Several ‘generic DAO’ patterns have emerged as a result, such as the one described here. [...]

  58. [...] find that article. But it seems not working with injection of persistence [...]

Add a Comment