Spring Sending data-Rest POST to a sub-resource

Suppose I have the following structure:

@Entity class Person extends AbstractPersistable<Long> { String name String surname } @Entity class Task extends AbstractPersistable<Long> { String description @ManyToOne Person person } 

If I follow the correct HAL recommendations, I should not expose entity identifiers. Since I do not have a bi-directional relationship, I cannot PUT or PATCH until http://localhost:8080/persons .

Even if I created the relationship, I probably would not want to first POST Task before /tasks , and then PUT before /persons (mobile clients are going to kill me). But even then, I don’t have a Task ID even from the returned Entity, so I can PUT to the Person object. (I obviously can do the parsing, but I don't think this is appropriate).

I probably would not want to have a list of 1000 tasks in a Person object. Therefore, not exporting the Task object is actually not an option (and this means that PATCH will not work)

So, how can I associate Person with Task if I cannot get its identifier? What is the right approach?

+2
spring spring-data-rest spring-hateoas
source share
2 answers

If you want to associate a task with a Person, you need a link to the person.

Assume the user URI is http: // localhost / persons / 1

You can then assign the person to the task by simply passing this URI in the person attribute.

So, the message for the task may look like this:

 { "description": "some text", "person": "http://localhost/persons/1" } 

Spring-data-rest will look for a person and take care of everything else.

+2
source share

In the HAL, Links are used to refer to related resources, not identifiers, and the HAL must always return a reference to itself, which serves as its unique identifier.

If I'm not mistaken, you can also annotate the fields using DBRef, and links should be created for you.

If you want the related resources to actually appear in the rows with the data, you will need to create a project. See here for more details:

Spring REST download resource not showing related objects (sets)

And last but not least, if you want Projections to also contain links, you need to make a ResourceProcessor for them, see here:

How to add links to Spring REST data forecasts?

+1
source share

All Articles