Search code examples
javahibernatedesign-patternsdaodto

DAO pattern when using hibernate


We use hibernate in our application and like to use DAO pattern to implement the data layer of application. I have seen some suggestions on using ValueObjects/DTOs to return data from DAOs

public interface EmployeeDAO {
  List<EmployeeDTO> getEmployees();
}

What is the advantage of returning ValueObjects/DTOs instead of returning hibernate domain objects as

public interface EmployeeDAO {
  List<Employee> getEmployees();
}

Is it not a overkill to copy the data from hibernate object to value object and have two copies of same data in memory. What advantage does ValueObjects really add ?

Are ValueObjects just preferred between business and view layers are should these be used in DAOs

Thanks for any suggestions

Siva


Solution

  • DTOs should generally be avoided. They can be useful in some situations, though:

    • instead of returning a whole graph of objects, return ad hoc DTOs containing only the interesting information. This makes the code more self-documenting. Otherwise, especially when the returned entities are detached, it's hard to know which associations are loaded and which aren't.
    • When you have to return the result of a query which doesn't return entity instances (aggregations, etc.)
    • When using Hibernate entities at client-side isn't possible for technical reasons (no access to Hibernate libraries, etc.). Although in this case, it might be the role of the facade layer to transform entities into DTOs rather than the role of the DAO.