gpt4 book ai didi

java - 如何管理具有其他相关实体的实体的 API 端点?

转载 作者:行者123 更新时间:2023-12-02 08:40:37 26 4
gpt4 key购买 nike

我正在使用 Spring 构建 RESTful API。我正在阅读文档和教程,其中大多数示例中只有基本对象,我不知道如何将所有这些结合起来解决我当前的问题...

我不知道如何处理这里的两件事:

  1. 处理通过 HTTP 请求创建实体的最佳方式是什么?我应该在查询参数中发送正文中相关实体的 ID 吗?我应该发送整个对象吗?
  2. 在这种情况下,如果我单独发送相关实体的 ID,我相信 @Valid 注释会触发为无效,因为主体不具有对象该模型要求(在我的例子中,EmployeeCustomer)。

这是端点:

    @PostMapping("/orders")
ResponseEntity<EntityModel<Order>> createOrder(@Valid @RequestBody Order order) {
order.setStatus(Status.IN_PROGRESS);
Order newOrder = repository.save(order);

return ResponseEntity
.created(linkTo(methodOn(OrderController.class).getOrder(newOrder.getId())).toUri())
.body(assembler.toModel(newOrder));
}

我想要创建和验证的实体:

@Data
@Entity
@Table(name = "Orders")
public class Order {

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;

@NotBlank
@NotNull
private String description;

@NotBlank
@NotNull
private Status status;

@NotNull
@ManyToOne
@JoinColumn(foreignKey = @ForeignKey(name = "employee_id_fk"))
private Employee employee;

@NotNull
@ManyToOne
@JoinColumn(foreignKey = @ForeignKey(name = "customer_id_fk"))
private Customer customer;

protected Order() {}

public Order(String description) {
this.description = description;
this.status = Status.IN_PROGRESS;
}
}

预先非常感谢您的帮助。

最佳答案

What is the best way to handle the creation of my entity with an HTTPrequest? Should I send the IDs in the body, in the query params?Should I just send the entire object?

当我们在数据库中创建新记录时,我们不会在请求中发送Id,Id将根据@GenerateValue中定义的策略自动生成当您使用 orderRepository.save(order); 保存实体时,您只需传递包含要保存的所需详细信息的对象。

接收@RequesetBody有效负载的理想方法是使用DTO。我们可以根据需求创建DTO,可以指定Long或required类型的Id,而不是使用整个Object,例如CustomerEmployee

public class OrderDTO {

private Long id;

@NotBlank
@NotNull
private String description;

@NotBlank
@NotNull
private Status status;

@NotNull
private Long employeeId;

@NotNull
private Long customerId;

protected Order() {}

public Order(...) {
...
}
}

请求有效负载将为:

{
"id" : null,
"description" : "payload using DTO",
"status" : "yourStatus",
"employeeId" : 1,
"customerId" : 2
}

In this case, if I send the IDs separately, I believe the @Validannotation would trigger as invalid because the body would not havethe objects the model asks for (Employee and Customer, in my case)

@Valid 验证了我们为 @RequestBody

中使用的模态/DTO 指定的约束

关于java - 如何管理具有其他相关实体的实体的 API 端点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61412518/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com