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.