管理项目中调用API的DTO和BO。

huangapple go评论146阅读模式
英文:

Managing DTO and BO in a project calling an API

问题

我正在开发一个Java Web应用的后端层,基本上是一个RESTful API(使用Spring Boot)。在我的后端中,我调用另一个API(实际上是我的数据库)来检索和组合数据。处理GET请求的当前工作流程如下:

  1. 在我的API中接收请求。
  2. 调用另一个API(数据库),并将其JSON响应映射到DTO(数据传输对象)。
  3. 将DTO转换为BO(业务对象)以执行逻辑操作。
  4. 通过Spring Boot返回BO(它将其字段转换为JSON体并返回)。

我的问题是 <br>
遵循DTO/BO模式,“需要”我将BO转换为第二个DTO,其中包含要传输的数据吗?

基本上,这会在我的上述列表中添加一个步骤,在3和4之间: <br>
---> ... <br>
---> 3.5. 将BO转换为新的DTO <br>
---> 4. 通过Spring Boot返回DTO <br>

我之所以没有这样做的原因是因为转换对象两次似乎有点繁琐,但是DTO/BO模式可以让我控制应该返回哪些确切的字段。

英文:

I'm working on a backend layer of a webapp in Java which is essentially an RESTful API (using Spring Boot).
Within my backend I'm calling another API (essentially my database) to retrieve and combine data.
Current my workflow for handling a GET request looks the following

  1. Receive request within my API
  2. Call the other API (database), and map it's JSON response to a DTO
  3. Convert DTO to BO to perform logic on it
  4. Return BO via spring boot (which turns its fields into a JSON body and returns this)

My question is <br>
Would following the DTO/BO pattern,
"require" me to turn my BO into a second DTO, containing the data to be transferred?

Essentially this would add a step to my list above, between 3 and 4: <br>
---> ... <br>
---> 3.5. Convert BO to new DTO <br>
---> 4. Return DTO via sprint boot <br>

The reason I haven't done this is because it seems a bit intensive to convert objects twice, however to DTO/BO pattern would give me control over which exact fields should be returned.

答案1

得分: 1

spring返回的JSON主体本身就是DTO。如果您对该表示不满意,那么是的,您应该接管并为应用程序外部的传输创建自己的DTO。

这很可能是为了信息隐藏的目的。如果外部应用程序不应知道的字段(内部ID等),那么您将需要创建一个对象来隐藏这些信息。

如果您的BO恰好与您想要共享的内容相符,那么添加另一层映射,而这并不改变任何内容,对于Spring已经为您完成的工作来说并没有增加任何价值。

英文:

The JSON body that spring returns is itself a DTO. If you are unhappy with that representation, then yes, you should take control and create your own DTO for the transfer out of your application.

Most likely this would be for the purpose of information hiding. If there are fields that outside applications have no business knowing (internal ids, etc), then you will want to create an object that hides those things.

If your BO happens to align with what you want to share, then adding another layer of mapping that doesn't change anything adds no value above what spring is already accomplishing for you.

huangapple
  • 本文由 发表于 2023年3月31日 21:50:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75899310.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定