How to use jpa query to find a record from column which has @OneToMany relationship?
Post.class
public class Post {
@Id
private String id;
...
...
@OneToMany(cascade = CascadeType.ALL, mappedBy = "comment", fetch = FetchType.LAZY)
private Set<Comment> comments;
}
Comment.class
public class Comment {
...
...
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "comment", referencedColumnName = "id")
private Post post;
}
Is there any way to query on PostRepository
and find the Post
using commentId ?
CodePudding user response:
To find by commentId you just have to create a function in your repository interface :
List<Comment> findByPost(Post post);
Then when you query just add :
Post post = new Post();
post.setId(yourId);
repository.findByPost(post);
CodePudding user response:
Assuming that Comment
has the property String id
you could do this as follows:
public interface PostRepository extends JpaRepository<Post, String> {
List<Post> findByCommentsId(String id);
}
You can read more about this on: