views:

35

answers:

3

I have some persistence capable Java objects with all the @annotations in my web application. All these objects reside in a data layer. Is it a best practice to use these persistence objects as data transfer objects?

For example, if I want to pass back the data fetched from data store, should I directly return those persistence objects or should I manually copy data to a intermediary DTO and pass it back to other layers? Which approach would you suggest?

A: 

I have never needed the extra level of abstraction provided by copying the persistence instance to a different DTO class.

Tony Ennis
+1  A: 

If you are absolutely certain no copies will end up in the Session storage or will be persisted/migrated to another instance/whatever, there is no need to do it.

If you need to keep these objects over multiple sessions/requests then it makes sense.

Another use-case is when you need to decouple loginc and persistence layer very thoroughly (i.e. to swap different persistence layers) then the coupling through the annotations could be troublesome.

Peter Tillemans
+2  A: 

I would say that it is OK to do so (in fact the major advantage for these ORMs were to use these domain objects in different layers w/o having unnecessary DTOs) if you follow the following guidelines:

  1. You don't extend the session boundaries i.e., any changes related to database should always be done using the Data Access Layer you have defined and not through these passed objects in other layers.
  2. Any data that you need in other layer (layers above the Data Access Layer like Business Logic Layer and Presentation Layer) is pre-populated in these objects otherwise you will get exceptions according to the ORM behavior.
  3. Don't extend the session boundaries for resolving the issue mentioned in No. 2
Faisal Feroz
+1 well said. This is exactly how we use them in our product as well.
Tingu