3
votes

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

2

2 Answers

1
votes

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.
1
votes

The main advantage of using DTOs is that another layer of the application cannot modify the actual model objects, and hence change your data. You do it to preserve the integrity and security of your data. With that in mind, it can be worth it if you have tight requirements about who/how data can be modified.

If you don't have such requirements, you can certainly return model instances. Just be careful to not change those models when you don't want to.