mike-neckのブログ

Java or Groovy or Swift or Golang

Spring Data REST(+ Spring Data JPA)でPOSTする時のメモ

Spring Data REST + Spring Data JPA で こんなエンティティを作る。

@Entity
public class User {
  @Id
  @GeneratedValue(strategy = IDENTITY)
  private Long id;
  private String name;
}
@Entity
public class Message {
  @Id
  @GeneratedValue(strategy = IDENTITY)
  private Long id;
  @ManyToOne(optional = false)
  private User user;
  private String text;
}

このとき、新しい User を作る場合はこんな感じになる。

$ curl -X POST http://localhost:8080/user -H "Content-Type:application/json" -d "{\"name\":\"foo\"}"
{
  "name" : "foo",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/user/1"
    },
    "user" : {
      "href" : "http://localhost:8080/user/1"
    }
  }
}

Message を作る場合、 User の参照をどのように指定するかわからなかったのでググった。

user には userhref URL を指定するらしい。

$ curl -X POST http://localhost:8080/message -H "Content-Type:application/json" -d "{\"text\":\"hello\",\"user\":\"http://localhost:8080/user/1\"}"
{
  "text" : "hello",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/messages/1"
    },
    "message" : {
      "href" : "http://localhost:8080/messages/1"
    },
    "user" : {
      "href" : "http://localhost:8080/messages/1/user"
    }
  }
}