Java Spring Boot 中的补丁请求为 null ManyToOne

问题描述 投票:0回答:1

我有这个实体:

@Entity
public class Rating {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private Boolean isNa = false;
    private String comment = "";
    @Min(0)
    @Max(5)
    private Integer points;
    @ManyToOne
    @JoinColumn(name="audit_id", nullable=false)
    private Audit audit;
    @ManyToOne
    @JoinColumn(name="question_id", nullable=false)
    private Question question;
    // ....

}

当我在 PatchMapping 中执行 JsonPatch 时,字段 autdit 和 Question 被设置为 null,这又确保我无法保存评级。

这是我的补丁映射:

    @PatchMapping("/api/v1/ratings/{id}")
    public ResponseEntity<Rating> updateRating(@PathVariable("id") long id, @RequestBody JsonMergePatch patch) throws ChangeSetPersister.NotFoundException, JsonPatchException, JsonProcessingException {
        Rating entity = findRatingService.findRatingById(id).orElseThrow(ChangeSetPersister.NotFoundException::new);
        JsonNode entityJsonNode = objectMapper.convertValue(entity, JsonNode.class);
        JsonNode patchedEntityJsonNode = patch.apply(entityJsonNode);
        Rating patchedEntity = objectMapper.treeToValue(patchedEntityJsonNode, Rating.class);
        Rating updatedEntity = saveRatingService.saveRating(patchedEntity);
        return ResponseEntity.ok(updatedEntity);
    }

patchedEntity.audit
永远是
null

我的示例请求正文:

[
    {
        "op": "replace",
        "value": "foo",
        "path": "/comment"
    }
]

我还在控制器中尝试了稍微修改的形式。但我有点卡在这里,希望得到任何建议。

我尝试过

JsonPatch
而不是
JsonMergePatch

java spring-boot rest spring-data-jpa jackson
1个回答
0
投票

Ex Fauji 租车服务

@PatchMapping(“/ api / v1 / ratings / {id}”) public ResponseEntity updateRating(@PathVariable("id") long id, @RequestBody JsonMergePatch patch) 抛出 ChangeSetPersister.NotFoundException, JsonPatchException, JsonProcessingException { 评级实体 = findRatingService.findRatingById(id).orElseThrow(ChangeSetPersister.NotFoundException::new); JsonNodeEntityJsonNode = objectMapper.convertValue(entity, JsonNode.class); JsonNode patchedEntityJsonNode = patch.apply(entityJsonNode); 评级 patchedEntity = objectMapper.treeToValue(patchedEntityJsonNode, Rating.class); 评级 updateEntity = saveRatingService.saveRating(patchedEntity); 返回 ResponseEntity.ok(updatedEntity); }

© www.soinside.com 2019 - 2024. All rights reserved.