我有一个Post
实体,具有Comment
的集合,如下所示
@Entity
@Table(name = "post")
public class Post {
@Id
private Long id;
@OneToMany(
mappedBy = "post"
)
private List<Comment> comments= new ArrayList<>();
评论实体
Entity
@Table(name = "comment")
public class Comment{
@Id
private Long id;
@ManyToOne
@JoinColumn(name = "post_id")
private Post post;
private boolean enabled;
我正在使用Spring Data JPA存储库findById(Long id)
来获取Post
。当前,返回与该Comment
关联的所有Post
。但是所需的输出是仅提取具有Comment
属性等于enabled
的true
。
是否可以在Spring Data JPA信息库中过滤子集合?
我尝试了以下操作
findByIdAndCommentsEnabledTrue(Long id);
findByIdAndCommentsEnabled(Long id, boolean enabled);
但是他们都不起作用。
您可以尝试以下JPA查询吗?
List<Post> findByCommentsEnabled(boolean enabled);
@Query("select post from Post post
fetch join post.comments comm
where post.id = :postId and com.enabled = :enabled")
Post findPostWithCommentsEnables(@Param("postId") Long postId,@Param("enabled") boolean enabled);
一个干净的基于Hibernate的解决方案是使用@@ Where。下面是示例代码
@Entity
@Table(name = "post")
public class Post {
@Id
private Long id;
@OneToMany(
mappedBy = "post"
)
@Where(clause = "enabled = true")
private List<Comment> comments= new ArrayList<>();