简体   繁体   English

数据模型的 DTO 是否应该具有仅用于 Java 序列化的原始数据类型?

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

I have created a data model Student as follows:我创建了一个数据模型 Student,如下所示:

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. Name 是两个字符串的对象 - firstName 和 lastName,Grade 是一个枚举,Roll number 是两个整数的对象 - 班级号和座位号。 To store this data in DB, I am serializing this data as a JSON.为了将此数据存储在 DB 中,我将此数据序列化为 JSON。

So I have created a DTO.所以我创建了一个 DTO。 So my question is, can the DTO also have the same objects Name, Grade and Roll or should it be in primitive datatypes?所以我的问题是,DTO 是否也可以具有相同的对象 Name、Grade 和 Roll,还是应该使用原始数据类型?

The purpose of DTO is used to pack some data to transfer to other clients/systems across the network. DTO 的目的是将一些数据打包,以便通过网络传输到其他客户端/系统。 One of the popular use case is the WEB API .流行的用例之一是 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.所以以JSON WEB API为例,DTO的结构主要取决于你的API响应体结构和你用来将DTO序列化为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 .如果底层框架支持对某些非原始类型进行序列化(大多数现代人都会这样做),我看不出有任何原因您不使用此功能并限制自己仅在 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 .例如,在 DTO 中包含LocalDateTime是很常见的,然后框架将序列化为有效的 ISO 8601 数据字符串,例如2020-04-23T11:11:12.511Z Not to mention including a List / Set in the DTO.更不用说在 DTO 中包含List / Set了。

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.如果您限制自己只在 DTO 中使用原始类型,则不知何故意味着 JSON 响应中的所有内容都将变平并且不再有嵌套结构。在非常简单的情况下可能没问题,但当您数据模型更丰富一些,可以用一些嵌套结构更好地表达。

If you use primitives, it would be easier for you to map your DTO to DB Columns !如果您使用原语,您将更容易将 DTO 映射到 DB 列!

But, if you intend to store Json of your datamodel, then you can proceed with the Datamodel itself但是,如果您打算存储数据模型的 Json,那么您可以继续使用数据模型本身

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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