Best practice for references in DTOs and entities in Spring

dtoentityhibernatejpaspring

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.

Best Answer

These all eventually make it into a database having IDs anyway, so my vote is for IDs.

Object references can have the peculiar property of pointing to two different objects that are functionally equal. This is why you compare strings in Java using .equals(), which compares the characters in one string against the characters in the other; and not == which compares the two references and always returns false, even if the two strings have the same sequence of characters.

Object references are also not persistent; they only exist in memory. You can store an ID in a database, and successfully retrieve it.