Search code examples
springspring-data-restspring-restspring-hateoas

How do I post nested entity to Spring Data Rest without setting @RestResource(exported = false)?


I've read this answer as a solution to POSTing an entity with nested entities. But I want to make a RESTful POST request.

That is, I want nested entities to be represented with links.

As an example, suppose my client wants to POST a student:

class Student {
  String name;
  Address address;
}

RepresentationModel<Address> address = //feign call to get previously saved address from Spring Data Rest endpoint
Student student = new Student();
student.setName("name");
student.setAddress(address.getContent());
client.save(student); //feign call to save student

This last call fails because Spring Data Rest expects address to be represented as a URI instead of a nested object. How can I add the URI?

I've tried making the Student address field be of type RepresentationModel<Address> but this doesn't work. The server throws an error saying addressId can't be null.


Solution

  • So you have your Student:

    public class Student {
        private String name;
        private Address address;
    }
    

    and Address:

    public class Address {
        private String street;
        private String houseNumber;
        private String zipCode;
        ...
    }
    

    And because of the fact that Student has a relation to Address you either have to make the relation not required and you wouldn't need the Address in your POST request. Or it's required that the address is already persisted before you try to create the Student and therefore you need the Address in your POST call.


    So the flow would look like this:

    • Create the address with post -> Get the Id/URI back

    • With the Id/URI create the Student.

    And to implement this you have to adjust the object in the client to the required one. So create a Stundent that looks similar to the required json like this:

    public class Student {
        private String name;
        private URI addressReference //probably need to rename this or use JsonProperty annotation
    }