如何在控制器、服务和存储库模式中使用 DTO [英] How to use DTOs in the Controller, Service and Repository pattern

查看:36
本文介绍了如何在控制器、服务和存储库模式中使用 DTO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遵循控制器、服务和存储库模式,我只是想知道 DTO 从何而来.

I'm following the Controller, Service and Repository pattern and I'm just wondering where DTOs come into this.

控制器是否应该只接收 DTO?我的理解是你不想让外界知道底层的领域模型?

Should the controller only receive DTOs? My understanding is you wouldn't want the outside world to know about the underlying domain model?

领域模型到DTO的转换应该发生在控制器层还是服务层?

Should the conversion from domain model to DTO happen in the controller or service layer?

推荐答案

在当今使用 Spring MVC 和交互式 UI 进行编程时,Web 应用程序实际上有 4 层:

In today programming with Spring MVC and interactive UIs, there are really 4 layers to a web application:

  • UI 层(Web 浏览器、JavaScript)

  • UI Layer (Web Browser, JavaScript)

MVC 控制器,即使用 @Controller

MVC Controller, i.e. Spring components annotated with @Controller

Service Layer,即使用@Service

Service Layer, i.e. Spring components annotated with @Service

数据访问层,即使用@Repository

每次这些层中的一层与底层交互时,它们都需要发送/接收数据,通常是 POJO,以在层之间传输数据.这些 POJO 是 DTO,也就是数据传输对象.

Every time one of these layers interact with the underlying layer, they need to send/receive data, which generally are POJOs, to transfer the data between layers. These POJOs are DTOs, aka Data Transfer Objects.

层与层之间只应使用 DTO,它们不一定相同,例如服务层可能会将业务逻辑应用于从数据访问层接收到的 DTO,因此服务层 API 的 DTO 与数据访问层 API 不同.类似地,控制器可能会重新排列数据以准备呈现(分组、摘要等),因此发送到网络浏览器的数据与从服务层接收的数据不同.

Only DTOs should be used between layers, and they are not necessarily the same, e.g. the Service Layer may apply business logic to DTOs received from the Data Access Layer, so the DTOs of the Service Layer API is different from the Data Access Layer API. Similarly, the Controller may rearrange the data to prepare it for presentation (grouping, summaries, ...), so the data sent to the web browser is different from the data received from the Service Layer.

在完全抽象的情况下,数据访问层的 API 不应反映数据访问的技术,即它是否使用 JDBC、JPA、NoSQL、Web 服务或其他一些存储/检索数据的方法.这意味着实体类不应位于数据访问层之外.

With full abstraction, the Data Access Layer's API should not reflect the technology of the Data Access, i.e. whether it is using JDBC, JPA, NoSQL, a web service, or some other means of storing/retrieving the data. This means that Entity classes shouldn't make it outside the Data Access Layer.

大多数项目不需要这种抽象级别,因此 DTO 通常是一个实体类,并且从数据访问层一直流向控制器,在那里它被视图使用,或者发送到网络浏览器,编码为 JSON.

Most projects don't need that level of abstraction, so it is common for a DTO to be an Entity class, and to flow all the way from the Data Access Layer to the Controller, where it is used either by a View, or is send to the web browser, encoded as JSON.

这取决于项目的规模和复杂性.项目越大,让每一层尽可能抽象/独立变得越重要.

It depends on the size and complexity of the project. The bigger the project, the more important it becomes to make each layer as abstract/standalone as possible.

这篇关于如何在控制器、服务和存储库模式中使用 DTO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆