我需要一种方法来拥有一个与其关系实体同步的对象。例如,我有一个 Post 和 Comment 实体
@Entity
@Table(name = "posts")
@Data
public class Post{
@Id
private Long id;
private String title;
private String content
@OneToMany(fetch = FetchType.EAGER)
List<Comment> comments = new ArrayList<Comment>();
}
@Entity
@Table(name = "comments")
@Data
public class Post{
@Id
private Long id;
private String content;
@ManyToOne(fetch = FetchType.LAZY)
private Post post;
}
假设该帖子有 4 条评论。并且在 PostsService 中有一个带有 Post 的对象并打印了评论数,它打印了 4。但是当我以相同的方法删除 2 条评论并打印评论数时,它仍然打印 4。
我怎么能有一个同步的对象,如果我删除评论,帖子对象也会得到更改。
// Post service class
public void someMethod()
{
Post post = postRepository.findById(1);
System.out.println( post.comments.size() ); // Prints 4
// CODE TO DELETE TWO COMMENTS
System.out.println( post.comments.size() ); // Still Prints 4
}