Are DAOs still needed in Spring MVC with JPA/Hibernate

Solace :

I know that this question has been asked countless times, but since most of the questions on this subject are 6-7 years old, I was hoping to see if there are any changes in the original arguments for/against this topic as newer versions of JPA came out. I know that this can be seen as primarily opinion based, but I am looking for a list of pros/cons.

Some people have argued that the entitymanager is a DAO in and of itself, and that a DAO layer in your application would be redundant. Most people would agree that the EntityManager covers basic CRUD operations very tightly...but there is a point that we should not be using entitymanager.createQuery(...) inside the service layer.

But now with the @NamedQueries annotation, we can simply add named queries to the model class and maintain a set of custom criteria queries for each entity model. For example, if we had a User class we can have something like

@Entity
@NamedQueries({
  @NamedQuery(name="User.findByUsername", query="SELECT u FROM User u WHERE u.username_lowercase = LOWER(:username)")
})
public class User{

@Column
private String username;

}

By storing the custom criteria queries inside of the model classes, we can avoid re-writing the same queries over and over again in the service layer - which makes the DAO layer seem even more unnecessary now.

The reasons that I have found to include the DAO layer are now:

  • You can change the persistence mechanism in the future more easily by having a central point that maintains data access (i.e generic DAO)
  • Easier time unit testing

I was wondering if anyone could contribute to this list as I am not sure if I should be using a DAO layer in my application

Bohdan Levchenko :

Ok, my assumption is that people who argued that the EntityManager is a DAO, injects entity manager directly to their services and manipulating it from there.

So as far as they are using just crud operations — EntityManager + @NamedQueries approach is good enough.

But once they put an extra logic say pagination or some security checks or projections to a some sort of DTO's (just to avoid fetching of unnecessary fields) they will reinvent the DAO within service layer and as you mentioned this piece of logic has to be tested and it has to be decoupled in some way.

So if you have only CRUD-style application, you can just omit using DAO layer and it is fine, but try to think a little bit upfront and predict possible complications.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=457088&siteId=1