What is the difference between a DTO and an Entity? In details these are my questions:
What fields should the DTOs have? For example my entity classes are:
@Entity public class MyFirstEntity implements Serializable { @Id @GeneratedValue private Long id; private String stringData; @OneToOne private MySecondEntity mySecondEntity; @OneToMany private List<MySecondEntity> mySecondEntitesList; } @Entity public class MySecondEntity implements Serializable { @Id @GeneratedValue private Long id; private Integer integerData; @ManyToOne private MyFirstEntity myFirstEntity; }
There is a one-sided connection (One-to-one) and a two-sided connection (Many-to-one), a simple String and Integer data and of course the ids. What to put from them in the MyFirstDTO
and MySecondDTO
classes?
If there is an inheritance between the entities, then how should I represent it in the DTOs? For example:
@Entity public class MyFirstEntity extends MySecondEntity { .... } @Entity public class MyFirstDTO extends MySecondDTO { .... }
How should I use them? For example, I find out this: I'm working on a web project. The user of the webpage wants to register. He/She fills the forms, and sends it to the server. On the server side I create first a DTO, because its fields have the validations. From the DTO I create an Entity and persist it to the database. When there is a request for an entity, I convert the requested entity to DTO, and give it to the user on the client side. Is it a good imagination, or not?