如何通过Spring Data JPA中的子集合属性之一过滤子集合

问题描述 投票:0回答:2

我有一个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属性等于enabledtrue

是否可以在Spring Data JPA信息库中过滤子集合?

我尝试了以下操作

findByIdAndCommentsEnabledTrue(Long id);
findByIdAndCommentsEnabled(Long id, boolean enabled);

但是他们都不起作用。

spring hibernate jpa spring-data-jpa querydsl
2个回答
0
投票

您可以尝试以下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);

0
投票

一个干净的基于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<>();
© www.soinside.com 2019 - 2024. All rights reserved.