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?
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);
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:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.