我们可以通过不创建DTO对象的JSON请求来保护域模型吗? [英] Can we protect a Domain Model from JSON request not creating a DTO object?
问题描述
对于Web/JSON请求,我们不想向客户端公开整个域模型.这种情况下的一种模式是使用DTO对象,然后从域模型映射到DTO,然后再映射回来.
For Web/JSON requests we don't want to expose the entire domain model to the client. One of the patterns in this case is using a DTO object and then mapping from domain models to DTOs and back.
DTO的示例是用于JSON请求的LoginUserDTO:
The example of DTO is LoginUserDTO that is used in JSON requests:
public class LoginUserDTO {
private String email;
private String password;
}
此外,我们将用户POJO注释为具有更多属性的Entity.通过使用LoginUserDTO,我们可以保护要更新的User实体的其他字段
In addition we have a User POJO annotated as Entity with much more properties. By using LoginUserDTO we protect other fields of the User entity to be updated
但是,具有多个DTO会导致代码重复,是否有可能避免这种重复?我正在使用带有Spring Data的Spring/Hibernate
However, having multiple DTOs creates code repetition, would it be possible to avoid this repetition? I am using Spring/Hibernate with Spring Data
推荐答案
这不是一个聪明的解决方案,但是对于某些特定情况,可能有人会有用.
您可以编写JSON类,并从POJO类扩展它们.例如;
You may write JSON classes and extend them from POJO classes. For instance;
public class LoginUserAsJSON {
private String email;
private String password;
}
public class LoginUserAsPOJO extends LoginUserAsJSON {
private int userId;
private Date loginTime;
...
}
这篇关于我们可以通过不创建DTO对象的JSON请求来保护域模型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!