在 Spring Boot 2 中,当实体具有外键时,如何构造一个 curl 请求以 POST(创建)实体?

In Spring Boot 2, how do I construct a curl request to POST (create) an entity when it has foreign keys?

我正在使用 Spring Boot 2、Java 11 和 PostGres 10。我有以下实体。注意它有几个多对一的外键约束...

@Data
@Entity
@Table(name = "Cards")
public class Card {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private UUID id;

    @ManyToOne
    private Occasion occasion;
    
    @Lob
    private byte[] image;
    
    @ManyToOne
    private User author;
}

我构建了以下控制器以允许创建和编辑该实体...

@RestController
@RequestMapping("/api/card")
public class CardController {

    @Autowired
    private CardService cardService;
    
    @GetMapping("/{id}")
    public ResponseEntity<Card> read(@PathVariable("id") UUID id) {
        Card foundCard = cardService.findById(id);
        if (foundCard == null) {
            return ResponseEntity.notFound().build();
        } else {
            return ResponseEntity.ok(foundCard);
        }
    }
    
    @PostMapping
    @ResponseStatus(code = HttpStatus.CREATED)
    public void create(@RequestBody Card card) {
        cardService.save(card);
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<Card> update(@RequestBody Card card, @PathVariable UUID id) {
        final Card updatedCard = cardService.update(id, card);
        if (updatedCard == null) {
            return ResponseEntity.notFound().build();
        } else {
            return ResponseEntity.ok(updatedCard);
        }
    }
    
}

如何构建将实体提交到我的端点的 curl 请求?我试过以下...

curl -v --header "Content-type: application/json" --data '{"occasion_id": "a989055a-b4f4-11ea-a1d1-6a0000c30600", "author_id": "8cfd5756-00c0-478e-a9b5-2ce23e78ea70", "image": "Tom"}' --request POST "http://localhost:8080/api/card"

但这会导致消息出现 400 错误...

{"timestamp":"2020-06-23T02:00:53.893+00:00","status":400,"error":"Bad Request","message":"","path":"/api/card"}

是否可以调整我的 Java 代码或 curl 请求,以便我能够成功创建我的实体?

试试这个:

curl -v --header "Content-type: application/json" \
--data '{"occasion": {"id": "a989055a-b4f4-11ea-a1d1-6a0000c30600"}, "author": {"id": "8cfd5756-00c0-478e-a9b5-2ce23e78ea70"}, "image": "<base64 encoded image>"}' \
--request POST "http://localhost:8080/api/card"

这里的格式是 JSON of Card:

{
  "id": "...",
  "occasion": {
    "id": "...",
    ...
  },
  "image": <base64 encoded image>,
  "author": {
    "id": "...",
    ...
  }
}

你的 CURL 应该是

curl --location --request POST 'http://localhost:8080/api/card' \
--header 'Content-type: application/json' \
--data-raw '{
  "occasion": {
    "id": "a989055a-b4f4-11ea-a1d1-6a0000c30600"
  },
  "author": {
    "id": "8cfd5756-00c0-478e-a9b5-2ce23e78ea70"
  },
  "image": "Tom"
}'

您应该在两个对象中都有名为 id 的字段。