如何在 Spring Data JPA 中按其属性之一过滤子集合



我有一个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 数据 JPA 存储库findById(Long id)来获取Post。目前,将返回与该Post关联的所有Comment。但是所需的输出是获取那些属性等于trueenabledComment

。是否可以在 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);

一个干净的基于休眠的解决方案是使用@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<>();

最新更新