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

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

我不知道该如何处理两件事:

  1. What is the best way to handle the creation of my entity with an HTTP request? Should I send the IDs in the body, in the query params? Should I just send the entire object?
  2. In this case, if I send the IDs separately, I believe the @Valid annotation would trigger as invalid because the body would not have the objects the model asks for (Employee and Customer, in my case).

这是端点:

    @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;
    }
}

在此先感谢您的帮助。

评论
  • 那些过往
    那些过往 回复

    我认为最好不要在端点中直接使用实体模型。 最好在端点中使用DTO。

    有时您想增加或减少http参数的数量,或者想为输入参数创建一些复杂的验证方法。

  • non_at
    non_at 回复
    用HTTP处理创建实体的最佳方法是什么?   请求?是否应该在查询参数中的正文中发送ID?   我应该只发送整个对象吗?

    When we create a new record in the database, we don't send the Id in the request, Id will be generated automatically based on strategy defined in @GeneratedValue when you save the entity using orderRepository.save(order); You just need to pass the object with the required details that you want to save.

    在这种情况下,如果我分别发送ID,我相信@Valid   注释将触发为无效,因为主体将没有   模型要求的对象(在我的情况下为员工和客户)

    @Valid validated the constraints which we have specified for modal/DTO used in @RequestBody