Spring Data-Rest POST to sub-resource
Asked Answered
R

2

3

Lets say 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 proper HAL guidelines I'm not supposed to expose entity id's. Since I don't have a bi-directional relationship I cant PUT or PATCH to http://localhost:8080/persons.

Even if I did create the relation, I probably wouldn't want to first POST the Task to /tasks and then PUT to /persons, (mobile clients are going to kill me). But even then I don't have the Task ID even from the returned Entity so I can PUT to the Person entity. (I obviously can string parse but I don't think it's appropriate).

I probably wouldnt want to have a list of 1000 tasks in the Person entity either. So not exporting the Task entity is not really an option (and this means PATCH will not work)

So how am I supposed to associate the Person with the Task if I cannot get his id? What is the correct approach?

Rella answered 15/10, 2015 at 18:52 Comment(0)
J
4

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

Lets say the person URI is http://localhost/persons/1

Then you could assign the person to a task by just passing that URI in the person attribute.

So a post to Task could look like this:

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

Spring-data-rest will lookup the person and take care of the rest.

Junkie answered 24/10, 2015 at 16:28 Comment(1)
This trick really works. I was looking for this information for couple months. Do you remember where you learned it from?Foetor
P
1

In HAL Links are used to reference related resources not ids and a HAL entity should always return a Link to itself, which serves as its unique identifier.

If I'm not mistaken you can also annotate fields with DBRef and links should be generated for you.

If you want related resources to actually show up inline with data you'll have to draft a Projection. See more here:

Spring Boot REST Resource not showing linked objects (sets)

Last but not least - if you want Projections to also contain Links you'll have to make ResourceProcessor's for them, see here:

How to add links to Spring Data REST projections?

Palanquin answered 18/10, 2015 at 5:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.