Search code examples
javaspringrestspring-dataspring-data-rest

How to update reference object in Spring-data rest?


Example: class Course and Teacher having many-to-one relationship, how to change teacher for a certain course via Spring-data rest?

GET http://localhost:7070/study-spring-data/course/2

Response:

{
  "name" : "CSCI-338 Hardcore Java",
  "_links" : [ {
    "rel" : "course.Course.teacher",
    "href" : "http://localhost:7070/study-spring-data/course/2/teacher"
  }, {
    "rel" : "self",
    "href" : "http://localhost:7070/study-spring-data/course/2"
  } ]
}

GET http://localhost:7070/study-spring-data/course/2/teacher

Response:

{
  "_links" : [ {
    "rel" : "course.Course.teacher",
    "href" : "http://localhost:7070/study-spring-data/course/2/teacher/1"
  } ]
}

As above shown, course 2 is associated with teacher 1, how to change teacher to teacher 2?

I have tried:

successfully updated course name:

PUT http://localhost:7070/study-spring-data/course/2 with payload

    {
      "name" : "CSCI-223 Hardcore C++",
    }

unsuccessful when try to update reference object teacher:

PUT http://localhost:7070/study-spring-data/course/2/teacher

with payload

    {
      "_links" : [ {
        "rel" : "course.Course.teacher",
        "href" : "http://localhost:7070/study-spring-data/course/2/teacher/2"
      } ]
    }

Thanks!


Solution

  • How about something like this:

    curl -v -X PUT -H "Content-Type: text/uri-list" \
         -d "http://localhost:7070/study-spring-data/teacher/1" \
         http://localhost:7070/study-spring-data/course/123/teacher
    

    This is a way suggested by O'Reilly's Spring Data book.