繁体   English   中英

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

[英]How to use JPA findBy query on column mapped by @OneToMany relationship?

如何使用 jpa 查询从具有@OneToMany 关系的列中查找记录?

后.class

public class Post {
  @Id
  private String id;
  ...
  ...
  
  @OneToMany(cascade = CascadeType.ALL, mappedBy = "comment", fetch = FetchType.LAZY)
  private Set<Comment> comments;

}

评论.class

public class Comment {
  ...
  ...

  @ManyToOne(fetch = FetchType.LAZY, optional = false)
  @JoinColumn(name = "comment", referencedColumnName = "id")
  private Post post;
}

有什么方法可以查询PostRepository并使用 commentId 找到Post

要通过 commentId 查找,您只需在存储库界面中创建 function :

List<Comment> findByPost(Post post);

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

Post post = new Post();
post.setId(yourId);
repository.findByPost(post);

假设Comment有属性String id你可以这样做:

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

您可以在以下位置阅读更多相关信息:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM