Java EE Architecture - Are DAO's still recommended when using an ORM like JPA 2?

28,261

Solution 1

If I'm using an ORM like JPA2 - where I have my entities that are mapped to my database, should I still be using a DAO? It seems like a lot more overhead.

It is. And clearly, Java EE doesn't encourage using the DAO pattern when using JPA (JPA already provides a standardized implementation of the Domain Store pattern and there isn't much value at shielding it behind a DAO). I find the DAO to be anti-DRY in such situation.

So for simple cases (actually, most cases), I happily skip the DAO and I have no problem with that. For more complex cases (for example when using stored procedures, flat files), I'd use it. In other words, it depends, as summarized in Has JPA Killed the DAO?. See also the related questions below:

Related questions

(...) One that contains session beans that implement my DAO's

Noooo, you certainly don't want to implement a DAO as a Session Bean:

  • You don't want to create as much (pooled) Session Bean as tables (big waste of resources)
  • You don't want to chain Session Beans everywhere, don't reproduce errors from the past, this is a known bad practice that doesn't scale well.

So if you really want to go the DAO way and want the EM to be injected, either implement your DAOs as Spring beans (in Java EE 5) or CDI managed bean (in Java EE 6).

You can have an in memory implementation of the DAO for unit testing your service layer.

If you really want to do unit testing, mock the DAO/EntityManager, there is no difference. And if you want to do integration testing, you can configure JPA to use an in memory database. So at the end, I just don't buy this argument.

It separates business logic from database access logic

Honestly, I don't see a big difference between relying on a DAO vs an entity manager, I don't see how a DAO separate things "better". Again, I don't buy this argument.

And to my experience, changing the underlying persistence solution is a very exceptional event and I'm not going to introduce DAOs for something that is very likely not going to happen (YAGNI, KISS).

Is there no middle ground here? Has anyone come across an architecture or implemented an architecture that meets some of the benefits of a DAO layer (most importantly the unit testability of business logic) that I mentioned above, but doesn't involve all the overhead involved to implement a DAO layer?

I don't see much middle ground and, as strongly hinted, I don't use DAOs if I don't feel the need. And as I said, mock the EntityManager if you want to truly unit test the business logic. It works for me and I'm happy to write less code.

More resources

Solution 2

For the record.

For Single responsibility principle (SRP), DAO is a must have, it separates the model and logic in a persistence layer that can be easily portable.

If a project is using Test Unit then DAO helps to test it correctly (mockup, database testing and so on).

DAO is a SERVICE and like one, we could wrap our process in a nicely class that is easy to maintenance.

JPA reduces the number of lines of codes but, nothing more, the old rules still applies.

JPA brings a repository layer but its not OUR repository layer. In the same principle, let's say that we encapsulated a logic that obtain the profit of some process. May be the encapsulation is simply a multiplication for 0.1 but its still worthy to encapsulate.

For example, let's say that i have the next problem : for some odd reason, i can insert a new Client in the database?. Where should i start to test?. a: ClientDao if exists, if not, then good luck finding elsewhere.

Share:
28,261

Related videos on Youtube

Brian DiCasa
Author by

Brian DiCasa

Web application developer with a passion for technology. Focus on web standards and server architectures. Enjoy the creation of complex applications that push the boundaries of what the web can do. Specialties include: Web Applications, Java, Server Architectures, Web Standards (HTML, CSS, JavaScript), JavaScript Libraries/Frameworks

Updated on July 09, 2022

Comments

  • Brian DiCasa
    Brian DiCasa almost 2 years

    If I'm using an ORM like JPA2 - where I have my entities that are mapped to my database, should I still be using a DAO? It seems like a lot more overhead.

    For example, I would need to maintain three extra packages:

    1. One that specifies my domain objects (which pretty much map my Entity objects):

      public class Employee {
          private String firstName;
          private String lastName;
          ...
          // Getters and setters
      }
      
    2. One that contains interfaces that specify my DAO methods

      public interface EmployeeDAO {
          public void addEmployee(Employee employee);
          public Employee getEmployeeById(long id);
          ...
      }
      
    3. One that contains session beans that implement my DAO's

      public EmployeeJpaDAO implements EmployeeDAO {
          interface method implementations here
          ....
          private method that transform my Employee entity into my Employee domain object
      }
      

    Now that's a lot of extra baggage to add every time I need to perform a new CRUD operation.

    However the benefits I see from having a DAO is:

    1. You can have an in memory implementation of the DAO for unit testing your service layer. This means you don't need to access the database to test business logic, and you can be assured that your objects will always contain the same values for properties

    2. It separates business logic from database access logic

    The option that doesn't involve implementing a DAO is to just use entity objects and EntityManager in the service layer:

    @Stateless
    public class EmployeeEjb {
        @PersistenceContext(unitName = "employee")
        private EntityManager manager;
    
        public Employee getEmployeeById(long id) {
            return manager.createNamedQuery(Employee.GetEmployeeById).getResultList();
        }
        ...
    }
    

    Is there no middle ground here? Has anyone come across an architecture or implemented an architecture that meets some of the benefits of a DAO layer (most importantly the unit testability of business logic) that I mentioned above, but doesn't involve all the overhead involved to implement a DAO layer?

    Thanks for any recommendations and/or suggestions! I'm really curious to see what some people have come up with in regards to this.

  • Brian DiCasa
    Brian DiCasa over 13 years
    Thanks for the informative response. I've asked another question about how to unit test EJB's when using JPA w/o a DAO, if you want to have a look at it. :D stackoverflow.com/questions/3834307/…
  • DavidS
    DavidS about 9 years
    JPA already separates the model and logic from the persistence layer. You want to separate it again, and that's fine and often useful, but that's not the DAO pattern. You're just redefining the pattern to describe your implementation. What you're describing sounds more like a facade, a more general pattern.
  • magallanes
    magallanes about 9 years
    Not specifically JPA is a separation of layer. For example, if i want to insert a entity Customer, its not as simple as em.Persist(customer), i require to "factory" or "inject" the Entity Manager, then i require to wrap inside a try catch the function and may be i need to create (and close) a transaction. And it is if in a simple example
  • DavidS
    DavidS about 9 years
    Agreed, but the DAO pattern is a special case. If we say that a DAO is anything that encapsulates a database and exposes an API, that's not a useful definition, because it's not specific enough.
  • Evandro Pomatti
    Evandro Pomatti almost 9 years
    Why is implementing DAOs as SLSB a bad practice regarding scalability? Which problems are associated with that and at which "scale" an application would present such a problem? I am terrified by using Spring in a Java EE environment, that is also reproducing a big error from the past....
  • Loa
    Loa over 7 years
    @Pascal I know it's been years since your answer, but from what I'm seeing, you've mixed DAO and service. I'm new at it, and I wonder how it's done. If this is not an inconvenience, could you show me some code sample, please. I really want to understand how this can be productively implemented. I want to learn this. I think you might be right. I just want to understand why, so I can vote for your answer. Do you have or know a Git example of some system that do this? Thank you.
  • Walfrat
    Walfrat over 6 years
    oh well, glad that my what I though was shared already some years ago, too bad I didn't found that back then I lost quite some time wondering if it was a good idea since it doesn't match the "classics" where you have a DAO layer developped yourself. Also note that if you can handle the searchs in your application as a different component, it reduce even more the needs for a DAO layer. However EntityManager alnoe is a bit short for the whole DAO Layer, you may add at least the JPAListener along with it. Because of the nature of managed entities you will need them to intercept every write.