如何在@OneToMany关系映射的列上使用JPA findBy查询?

问题描述 投票:0回答:2

如何使用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
吗?

java spring-boot hibernate jpa spring-data-jpa
2个回答
3
投票

假设

Comment
具有属性
String id
,您可以按如下方式执行此操作:

public interface PostRepository extends JpaRepository<Post, String> {
    List<Post> findByCommentsId(String id);
}

您可以阅读更多相关内容:


0
投票

要通过 commentId 查找,您只需在存储库界面中创建一个函数即可:

List<Comment> findByPost(Post post);

然后当您查询时只需添加:

Post post = new Post();
post.setId(yourId);
repository.findByPost(post);
© www.soinside.com 2019 - 2024. All rights reserved.