I have two entities, Post and Comment.
Post entity:
@Entity
@Table(name = "posts")
public class Post {
@Id
@GeneratedValue
private Long id;
private String title;
private String content;
@OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Comment> comments = new ArrayList<>();
Comment entity:
@Entity
@Table(name = "comments")
public class Comment {
@Id
@GeneratedValue
private Long id;
private String content;
@ManyToOne
@JoinColumn(name = "post_id")
private Post post;
Left out getters and setters for readability.
When I send a POST-request via PostController, I can store a new Post in my PostgreSQL database. How do I add new Comments to this Post via Controller? I seem to not find the answer anywhere.
So, here you have create a two way relationship and hence will need to update both the post entity and comment entity.
let take for instance that your comments path is /post/{postId}/comment
, and you are using Sping JPA (with repositories for comment
and post
as commentRepository
and postRepository
respectively.)
then controller method will look like -
@PostMapping("/post/{postId}/comment")
public ResponseEntity postController(@PathParam("postId") Long postId,
@RequestBody Comment comment) {
Post post = postRepository.getById(postId);
comment.setPost(post);
post.getComments().add(comment);
commentRepository.save(comment);
postRepository.save(post);
}
Another alternative is to create a one way relationship, so
@Entity
@Table(name = "posts")
public class Post {
@Id
@GeneratedValue
private Long id;
private String title;
private String content;
@Entity
@Table(name = "comments")
public class Comment {
@Id
@GeneratedValue
private Long id;
private String content;
@ManyToOne
@JoinColumn(name = "post_id")
private Post post;
Then, you only need to update the comment entity on POST-request and if you need to get all the comments for a post you can do -
List<Comment> comments = commentRepository.getByPostId(postId);