Spring Data-Rest POST to sub-resource

梦想与她 提交于 2020-01-04 23:06:21

问题


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?


回答1:


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.




回答2:


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?



来源:https://stackoverflow.com/questions/33156283/spring-data-rest-post-to-sub-resource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!