2

I can't figure out how to add a child entity (lets say a comment entity to a parent post entity) using Spring-Data-Rest when the relationship between them is one-to-many + unidirectional (specifically from the parent to the child) and when the database uses a non-nullable join column on the child entity table.

For linking two entities in a relationship using Spring-Data-Rest, I believe the normal way is to first create both entities (with a POST call to their respective endpoints) and then link them with a PUT or PATCH to the relationships endpoint, such as /api/posts/1/comments. That link request's body would contain a link to the previously created child entity, like http://localhost:8080/api/comments/1. However, for my situation with a non-nullable join column on the child entity, when I try to create the child entity I am unable to because it can't be inserted into the database with a null value for the parent_id join column.

@Entity
public class Post {
  @Id
  private Long id;

  private String title;

  @OneToMany
  @JoinColumn(name = "post_id", nullable = false)
  private List<Comment> comments;
}
@Entity
public class Comment {
  @Id
  private Long id;

  private String message;
}
@RepositoryRestResource
interface PostRestRepository implements JpaRepository<Post, Long> {}

@RepositoryRestResource
interface CommentRestRepository implements JpaRepository<Comment, Long> {}

When trying to create the child entity via a POST call to /api/comments, I receive this error in the response body: ERROR: null value in column \"post_id\" violates not-null constraint.

I am assuming there is a way to create and link a comment to a post in this scenario, but I haven't been able to find an answer anywhere.

Joe
  • 279
  • 1
  • 5
  • 11

1 Answers1

1

You can send an array of URIs of existing Comment resources as the value of the comments field when creating a new Post resource, like this:

POST /api/posts

{
  "title": "My Post",
  "comments": [
    "http://api-url/comments/1",
    "http://api-url/comments/2"
  ]
}

Unfortunately, this essential piece of information seems to have been omitted from the SDR documentation. However, you can find it in the source code.

There is an open issue regarding the lack of documentation dating back to 2017.

Mathis
  • 31
  • 4
  • Hey @Mathis, this is a useful technique. But my main question was related to "how can I create a Comment that is immediately connected to a Post" so that I can have the foreign key in the database set to NOT NULL. From my understanding now, it may not be possible to have the foreign key NOT NULL if both entities are `@RepositoryRestResource`s. – Joe Jul 24 '20 at 03:46