在 Spring Boot 中将一组 ID 或一组对象作为 DTO 中的数据传递?
我正在尝试创建一个项目管理应用程序,对于我的后端,我有一个项目实体,它与用户实体具有多对多关系。我有以下 DTO:
public class ProjectDto implements Serializable {
private final Long id;
private final String name;
private final String description;
private final Date createdAt;
private final Date updatedAt;
private final Set<UserDto> users;
}
在我的 ProjectService 中,我想要一种方法来创建一个项目,并为其分配任何已发送的用户。但是,我的问题是我的前端应该向后端发送一组用户对象,还是最好发送一组我想要分配给该项目的用户 ID?在创建项目时实际返回此 DTO,并在我想要创建项目时使用另一个带有一组用户 ID 的 DTO,这不是更好吗?
I am trying to create a project management app and for my back-end I have a Project Entity which has a many-to-many relationship with the User Entity. I have the following DTO:
public class ProjectDto implements Serializable {
private final Long id;
private final String name;
private final String description;
private final Date createdAt;
private final Date updatedAt;
private final Set<UserDto> users;
}
And in my ProjectService I want to have a method which creates a project having any sent users assigned to it. However, my question is should my front-end send to my back-end a set of user objects or is better to send a set of IDs of the users I want to assign to this project ? Is it not better to actually have this DTO returned when a project is created and have another DTO with a set of user ids for when I want to create a project ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

我们不能信任来自前端的数据,应该对请求正文应用验证,包括
Set用户。并验证
Set用户
我们必须使用可信数据——来自数据库或其他BE源。并使用
Set; userIds
也需要从数据库获取,但我们不必添加更多代码来验证 DTO,并且验证 ID 更简单且易于维护。使用
userIds
也是为了确保设置为project
的user
是从数据库获取的实体。它还使 FE 代码更简单(我希望),因为不必构建(DTO)对象We cannot trust data from front-end and should apply validations for the request body including
Set<UserDto> users
. And to validate theSet<UserDto> users
we have to use trusted data - from DB, or other BE sources.And using
Set<?> userIds
also needs to fetch from DB, but we don't have to add more code to do validate the DTO and validating the IDs is more simple and easy to maintain.Using
userIds
is also to make sure theusers
that set toproject
are entities that fetched from DB. It also keeps the FE code simpler (I hope) as not having to build the (DTO) object