Should a DTO in a composite DTO refer to each other using a primary key or an object reference?

There is a recommendation that transfer objects should not contain references to objects of other transfer objects . Instead, they should use the primary keys of other transfer objects as foreign key fields.

A simple example with Customer and Customer as entities

Obviously, an OrderListDTO containing a list of orders without customer information will contain foreign keys to customer details.

The composite DTO OrderWithCustomerDTO will have references to the OrderDTO and CustomerDTO objects. But should the built-in OrderDTO have an object reference to its CustomerDTO in this case? Or should he use the primary key of the customer?

Indication of links to objects

One of the advantages is that the client can directly use the sending object, for example. as a presentation model. I tend to take this approach for transport objects that are always completely autonomous, for example. Composite DTO with associated DTO or full tree. The client can count on self-condensation. The client does not have to fully process the transferred object.

Indication of primary keys as foreign keys

The advantage is that internal and external links are treated the same way. I tend to require such an approach to transfer objects that may contain external links, for example. subtree with external children. The client must iterate over the complete list to allow external children.

A more complex example with a tree or subtree

The transmission object is now a tree or subtree. Technically, this is a list of nodes.

Well, if the nodes in the transmitting object refer to each other using object references, for example, to NodeTOWithObjectReferences below?

public class NodeTOWithObjectReferences implements Serializable { private long id; private NodeTOWithObjectReferences parent; private List<NodeTOWithObjectReferences> children; } 

Or should the transferred object replace the EACH object reference to the foreign key field, for example, NodesTOWithForeignKeys below?

 public class NodesTOWithForeignKeys implements Serializable { private List<NodeDetail> children; } public class NodeDetail implements Serializable { private long id; private long parentId; private List<Long> childIds; } 


(I selected the transfer objects to encapsulate the domain model from clients and provide specific representations of client data.)

+4
source share
1 answer

As a general recommendation, transmission objects should not contain object references to other objects. Instead, they should use the primary keys of other objects as the foreign key of the field.

Could you please attach a link to the source of this recommendation? This is at least not obvious to me.

In my current project, I am using transfer objects that contain references to objects. This is convenient, and I have not encountered any problems with this approach.

+3
source

Source: https://habr.com/ru/post/1340425/


All Articles