How do I prevent Hibernate from deleting child objects not present in a JSON post?

前端 未结 1 1593
心在旅途
心在旅途 2020-12-07 05:59

I have a JPA Property entity that has children (multiple Rate\'s and multiple Reservation\'s). In my JavaScript application, I pull

1条回答
  •  有刺的猬
    2020-12-07 06:12

    Late answer, however if you are using a Spring MVC Rest controller to handle the update rather than a Spring Data Rest controller then it would appear the former does not support partial updates/patch requests.

    Working with traditional non-restful web apps modifying entities directly via a form this is of course possible. For example:

    @RequestMapping
    public String updateEntity(@ModelAttribute myEntity){
      //submitted form parameters merged to existing entity 
      //loaded via getMyEntity() leaving unmodified fields as they were
    }
    
    @ModelAttribute
    public MyEntity getMyEntity(){
      //load some existing entity
    } 
    

    However when binding JSON to an Entity via @RequestBody this is not possible:

    @RequestMapping
    public String updateEntity(@RequestBody myEntity){
      //new instance instantiated by the Jackson mapper
      //missing fields will be null
    }
    

    There are some outstanding JIRAs around this:

    https://jira.spring.io/browse/SPR-13127

    https://jira.spring.io/browse/SPR-10552

    https://jira.spring.io/browse/SPR-13127

    And various SO questions:

    Spring Partial Update Object Data Binding

    The good news however is that Spring Data Rest does support partial updates via patch so if it is an option to expose your repository as a Rest Repository then you should be able to achieve the required behaviour:

    https://spring.io/guides/gs/accessing-data-rest/

    PUT replaces an entire record. Fields not supplied will be replaced with null. PATCH can be used to update a subset of items.

    0 讨论(0)
提交回复
热议问题