如何使用 Spring Data JPA 过滤 OneToMany 字段?

How to filter a OneToMany field using Spring Data JPA?

我正在尝试根据 post 是否设置为隐藏来过滤掉与某个类别关联的 post。

我可以使用 post-query 过滤器来做到这一点(见下文),但我想知道是否可以使用 JPA 方法构造查询? (特别是查询构建方法,如 FindAllBy...,我希望通过坚持使用这些类型的查询来保持数据库不可知)

我也可以在 PostRepository 上调用 FindAllByCategory 并以这种方式构建 return,但感觉很笨拙和倒退。

总而言之,我想找到一种方法来声明 FindAllAndFilterPostsByIsHidden(boolean isHidden)

类别Class

@Entity
public class Category {

    public Category(String name, Post... posts) {
        this.name = name;
        this.posts = Stream.of(posts)
            .collect(Collectors.toSet());
        this.posts.forEach(post -> post.setCategory(this));
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String name;

    @OneToMany(mappedBy = "category")
    private Set<Post> posts;
}

Post Class(为简洁起见,只保留基础知识)

@Entity
public class Post {

    public Post(Category category, boolean isHidden) {
        this.category = category;
        this.isHidden = isHidden
    }

    @ManyToOne
    @JoinColumn
    private Category category;

    private boolean isHidden;
}

现在我这样做是为了过滤与 CategoryController

中的类别关联的 post
@GetMapping
    public List<Category> list(Authentication authentication) {
        boolean canViewHidden = securityService.hasAuthority(Permissions.Post.VIEWHIDDEN, authentication.getAuthorities());
        List<Category> categories = categoryRepository.findAll();
        categories.forEach(
            category -> {
                Set<Post> filteredPosts = category.getPosts().stream()
                    .filter(post -> canViewHidden || !post.isHidden())
                    .collect(Collectors.toSet());
                category.setPosts(filteredPosts);
            }
        );
        return categories;
    }

我会尝试在您的 JPA-Repository 中为 Post Class 使用自定义查询,如下所示:

@Query(value = "SELECT p FROM Post p INNER JOIN Category c ON p.id = c.post.id "
        + "WHERE p.hidden = false AND c.id = :id")
List<Post> findViewablePostsByCategory(@Param("id") Long categoryId);

我知道这可能不是您正在寻找的确切方法,但正如 K.Nicholas 指出的那样,无法将联接与 JPA-Repositories.[=11= 的查询构建方法一起使用]