java - 在 Spring Boot 和 PostgreSQL 中使用 OneToMany 关系
问题描述
我有两个实体,发布和评论。
发布实体:
@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<>();
评论实体:
@Entity
@Table(name = "comments")
public class Comment {
@Id
@GeneratedValue
private Long id;
private String content;
@ManyToOne
@JoinColumn(name = "post_id")
private Post post;
为了便于阅读,省略了 getter 和 setter。
当我通过 PostController 发送一个 POST 请求时,我可以在我的 PostgreSQL 数据库中存储一个新的 Post。如何通过控制器向这篇文章添加新评论?我似乎在任何地方都找不到答案。
解决方案
因此,您在这里创建了双向关系,因此需要同时更新帖子实体和评论实体。
例如,您的评论路径是/post/{postId}/comment
,并且您正在使用 Sping JPA(分别具有用于comment
和post
ascommentRepository
和的存储库postRepository
。)
然后控制器方法看起来像 -
@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);
}
另一种选择是创建单向关系,所以
@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;
然后,您只需要更新 POST-request 上的评论实体,如果您需要获取帖子的所有评论,您可以这样做 -
List<Comment> comments = commentRepository.getByPostId(postId);
推荐阅读
- ack - 搜索 .zst 文本文件
- mysql - Nodejs Mysql:Query-Escaping 添加单引号
- extjs - 如何在卡片布局中切换面板
- jquery - 使用 DOM 更新的 jQuery 动态变化
- c++ - 在可视化解决方案 C++ 中出现链接器错误
- java - YouTubePlayerSupportFragment 在画中画中停止并出现黑屏
- android - Android ListPreference 条目文本,而不是来自不扩展 PreferenceFragment 的 Activity 或 Fragment 的条目值
- javascript - 如何检测浏览器强制刷新事件 - 跨浏览器
- excel - VBA 根据相邻单元格值在散点图中显示每个标记
- django - 将 jira 对象从 django 视图方法传递给该会话唯一的另一个对象