0

Why should we keep Domain (DTO) separate from Entity classes when they the have same content? I know we use DTOs for UI and Entities for Hibernate, but we can implement Annotations in the DTO itself?

Tanuj Mathur
  • 1,408
  • 10
  • 20
Nikhil T
  • 11
  • 1

3 Answers3

2

You don't really have to create DTO's for it. My suggestion is to introduce DTO's when you have to change entities to display them on some other way than expected for the client.

http://www.adam-bien.com/roller/abien/entry/how_evil_are_actually_data

JPA Entities and/vs DTOs

Community
  • 1
  • 1
GregD
  • 1,884
  • 2
  • 28
  • 55
1

Implementing DTOs doesn't have to be painful. Take a look at Blaze-Persistence Entity Views to see reasons for doing it and how you can avoid most of the pain. In short, the most common reasons for using DTOs are

  • Lazy loading issues when exposing entities
  • The need for a specialized representation that doesn't match the source i.e. a string should be cut off after 250 chars in a DTO
  • Performance. You actually only need a subset of the fields in the DTO
Christian Beikov
  • 15,141
  • 2
  • 32
  • 58
0

If you use Entities directly you might run in various problems that you can solve by introducing a separate layer (although I wouldn't name them DTOs):

  1. The requirements for UI, Domain Logik and Database might (and in every non trivial project will) differ: Maybe you want to store stuff in a Blob, but want it as an object structure in the domain. Maybe you need an "isChanged" field for the UI, that you don't need to store in the database, because there it will always be false and so on.

  2. At least when your Entities are attached to a session, every change is scheduled for persistence in the database, this can be nice, if it is what you want, but it can also be rather annoying when you only want to store part of the changes.

Said that: It adds extra code, and if you don't have those or similar problems, there is nothing inherently wrong with not having DTOs.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348