Persistence entities as data transfer objects
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 da开发者_运维技巧ta 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?
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:
- 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.
- 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.
- Don't extend the session boundaries for resolving the issue mentioned in No. 2
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.
I have never needed the extra level of abstraction provided by copying the persistence instance to a different DTO class.
精彩评论