【问题标题】:How to use JPA findBy query on column mapped by @OneToMany relationship?如何在 @OneToMany 关系映射的列上使用 JPA findBy 查询?
【发布时间】:2022-01-20 08:11:41
【问题描述】:

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

Post.class

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


    【解决方案1】:

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

    List<Comment> findByPost(Post post);
    

    然后在查询时添加:

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

    【讨论】:

      【解决方案2】:

      假设Comment 具有String id 属性,您可以这样做:

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

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

      【讨论】:

        猜你喜欢
        • 2021-09-23
        • 2014-07-30
        • 1970-01-01
        • 1970-01-01
        • 2020-04-15
        • 1970-01-01
        • 2021-06-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多