10

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!

Liu
  • 103
  • 1
  • 6
  • amazing! It actually worked. I thought payload only accept header with "application/json". I can't find this in spring-data document though. Thanks a lot. – Liu Aug 01 '13 at 14:22

3 Answers3

15

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.

stites
  • 4,903
  • 5
  • 32
  • 43
Wirus
  • 1,140
  • 10
  • 10
  • Ah, they made updating a single reference look like adding new references to a collection. That's why it uses text/uri-list even though there's no list involved. –  Aug 28 '13 at 20:48
  • *Why* would you do that? Wouldn't that mean that your client takes control over associations? What if your client forgets to do that? – Stefan Falk Nov 18 '17 at 22:20
  • is there any way to do it in JSON format? – Yusril Maulidan Raji Aug 02 '21 at 11:33
0

I think you should have to check the Cascading for Course. Because if you are updating the course , then it should update your teacher also, if Cascading update or All is to be assigned for your course.

Ashish
  • 194
  • 1
  • 11
0

Using httpie PATCH instead of PUT works for me:

http PATCH :7070/study-spring-data/course/2 teacher="http://localhost:7070/study-spring-data/teacher/2"

Again, this does not work with PUT.

jansolo
  • 329
  • 3
  • 11