在 Spring Boot 中将实体与有效负载 (dto) 混合 - 最佳实践 [英] Mixing entity with payload (dto) in spring boot - best practice

查看:45
本文介绍了在 Spring Boot 中将实体与有效负载 (dto) 混合 - 最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让一个类同时作为实体(映射并存储在数据库中)和有效负载(对象序列化并从 REST 端点返回)是一种好习惯吗?

Is it good practice to have one class being both entity (mapped and stored in the database) and payload (object serialized and returned form REST endpoint) at the same time?

我听说实体永远不应该高于服务层,而应该映射到服务中的 DTO 对象,然后这些 DTO 应该返回给控制器.

I heard somewhere that entities should never go higher than service layer but rather should be mapped to DTO objects in services and then these DTO should be returned to controllers.

我个人认为这是不好的做法,因为在这样的类中,我们混合了用于序列化为 JSON 和将对象映射到数据库的注释,这使得代码难以阅读.

I personally think this is bad practice because in such class we mix annotations for serializing to JSON and for mapping object to the database which makes the code hard to read.

但也许还有其他一些争论.你怎么看?

But maybe there are some other arguments. What do you think?

推荐答案

我个人认为分层是一个很好的做法.我会通过以下方式来激励.

Personally I think it is good practice to separate the layers. I would motivate with the following.

假设您有一个客户,客户 A.

Lets say you have a client, client A.

客户端 A 通过 Restful 端点集成到您的系统中,并需要帐户信息.您对 Rest 端点进行版本控制并返回版本化的 Account 实体.

Client A integrates into your system via a Restful endpoint and expects account information. You version the Rest endpoint and return the versioned Account entity.

@Entity
public class Account {
   private Long id;
   private String firstname;
   private String lastname;

   //Getters and setters are omitted for the sake of brevity
}

客户 A 对信息感到满意并使用了 6 个月.

Client A is happy with the info and uses it for 6 months.

6 个月后,您的数据库团队开始清理/重构过程,并将姓氏更改为姓氏,将名字更改为姓名.以下需要更改,因为它们都可能接触到对象:

After the 6 months your database team starts a cleanup/refactoring process and changes lastname to surname and firstname to name. The following needs to change, because all of them might touch the object:

  1. 数据库层
  2. 持久层
  3. 业务层
  4. 展示层

如您所见,微小的变化引发了大量的变化.它还违反了版本化 Restful 端点的约定.

As you can see the small change trigger a lot of changes. It also breaks the contract of the versioned Restful endpoint.

如果在业务层中将实体转换为 DTO,则更改将包含在您的应用程序边界内并且影响最小.合同也保持不变,客户端无需更改.

If the Entity was converted to a DTO say in the Business Layer the changes will be contained inside your application boundary and of minimal impact. The contract also stays intact and no changes are needed on the client's side.

这篇关于在 Spring Boot 中将实体与有效负载 (dto) 混合 - 最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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