如何使用jpa查询从具有@OneToMany关系的列中查找记录?
课后
public class Post {
@Id
private String id;
...
...
@OneToMany(cascade = CascadeType.ALL, mappedBy = "comment", fetch = FetchType.LAZY)
private Set<Comment> comments;
}
评论.课堂
public class Comment {
...
...
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "comment", referencedColumnName = "id")
private Post post;
}
有什么方法可以在
PostRepository
上查询并使用commentId找到Post
吗?
假设
Comment
具有属性 String id
,您可以按如下方式执行此操作:
public interface PostRepository extends JpaRepository<Post, String> {
List<Post> findByCommentsId(String id);
}
您可以阅读更多相关内容:
要通过 commentId 查找,您只需在存储库界面中创建一个函数即可:
List<Comment> findByPost(Post post);
然后当您查询时只需添加:
Post post = new Post();
post.setId(yourId);
repository.findByPost(post);