Given the following architecture and frameworks: Spring Boot Application with Spring Data JPA (Hibernate is used as OR mapper); layered architecture as followed.
- REST layer
- Service layer
- Persistence layer (JPA)
DTOs are used to transfer the data between frontend and backend. Mapping for DTOs -> entity objects, entity objects -> DTOs do already exist.
My questions are:
- Should DTOs contain only the id as a reference to another object (DTO) or the other DTO object itself as reference type?
- Should entities contain only the id as a reference to another object (entity) or the enitity object itself as a reference type?
To be more precise, eg given an fictive application where orders and items exist. An order consists of multiple items. How should the corresponding DTO (1) and entity object (2) look like:
(1)(a)
public class OrderDTO { private Long id; private List<Long> items; // id of item entities // further stuff omitted } or
(1)(b)
public class OrderDTO { private Long id; private List<ItemDTO> items; // further stuff } whereas ItemDTO is
public class ItemDTO { private Long id; private String name; // further stuff } (2)(a)
@Entity public class Order { @Id // value generation strategy would be set here private Long id; // some JPA annotaions to reference the id column of items private List<Long> items; // further stuff omitted } or
(2)(b)
@Entity public class Order { @Id // value generation strategy would be set here private Long id; @OneToMany // further annotations private List<Item> items; // further stuff omitted } whereas Item is
@Entity public class Item { @Id // value generation strategy would be set here private Long id; private String name; // further stuff } I would be glad if you could share you best practices/opinion. Thanks.
@ManyToOne/@OneToManyetc. to link entities (and be careful about cascading etc.). There is not one best solution for any situation.@OneToManyetc as stated by you.