1

I have a JPA Property entity that has children (multiple Rate's and multiple Reservation's). In my JavaScript application, I pull JSON via REST {property:{rates:[...], reservations[...]}. Rates and Reservations are very verbose, so when I post a property update (like changing the name), I delete the rates and reservations from the JSON POST payload. I hoped that Hibernate would simply ignore the missing keys, but alas, it's removing all the children on save. How do I specify to Hibernate to ignore them if they're not there?

@Entity
public class Property {

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

    String name;

    @OneToMany(mappedBy = "property", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
    @JsonManagedReference
    private Set<SeasonRate> rates = new HashSet<>();

    @OneToMany(mappedBy = "property", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
    private Set<Reservation> reservations = new HashSet<>();

}

Ps: My understanding of cascades is limited, but I do actually want the functionality that if someone deletes a property, it must delete the rates and reservations. Nowhere do I update rates or reservations via a full property save though, so perhaps I should just use CASCADE=UPDATE? Rates have their own update mechanism and so do reservations.

sparkyspider
  • 13,195
  • 10
  • 89
  • 133

1 Answers1

1

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.

Community
  • 1
  • 1
Alan Hay
  • 22,665
  • 4
  • 56
  • 110