简体   繁体   中英

Should the DTO of a datamodel have primitive Data types only for serialization in Java?

I have created a data model Student as follows:

class Student {
private final Name name;
private final Grade finalGrade;
private final Roll rollnumber;
}

Name is an object of two Strings - firstName and lastName, Grade is an enum and Roll number is an object of two integers - class number and seat number. To store this data in DB, I am serializing this data as a JSON.

So I have created a DTO. So my question is, can the DTO also have the same objects Name, Grade and Roll or should it be in primitive datatypes?

The purpose of DTO is used to pack some data to transfer to other clients/systems across the network. One of the popular use case is the WEB API . So taking JSON WEB API as an example ,the structure of the DTO is mainly depends on your API response body structure and the capability of the underlying framework that you use to seraialzie the DTO to a JSON.

If the underlying framework supports serailzing some non primitive types (which most modern one will) , I don't see any reasons that you do not use this feature and restrict yourself to only use primitive data type in the DTO .

For example, it is very common to include a LocalDateTime in the DTO and then the framework will serialize to a valid ISO 8601 data string such as 2020-04-23T11:11:12.511Z . Not to mention including a List / Set in the DTO.

If you restrict yourself to only use primitive type in the DTO , it somehow means that all things in the JSON response will be flatten out and there is no more nested structure.It may be okay in a very simple case but not so good when your data model is a little bit richer which can be expressed much better with some nested structure.

If you use primitives, it would be easier for you to map your DTO to DB Columns !

But, if you intend to store Json of your datamodel, then you can proceed with the Datamodel itself

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM