Spring Data JPA Query中按子对象过滤时出错

我的代码结构如下所示。

文章:

@Entity public class NewsArticle{ @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; [Other class properties such as title, publisher, publishedDate, etc.] @OneToMany(mappedBy = "article") private Set userReadNewsArticles = new HashSet(); [Getters and Setters] } 

用户阅读的文章:

 @Entity public class UserReadNewsArticle { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; private Long readAccountId; private Long readArticleId; @JsonIgnore @ManyToOne private Account account; @JsonIgnore @ManyToOne private NewsArticle article; [Getters and Setters] } 

帐户:

 @Entity public class Account { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; [Other class properties] @OneToMany(mappedBy = "account") private Set userReadNewsArticles = new HashSet(); [Getters and Setters] } 

我希望在我的NewsArticleRepository中有一个查询方法来获取用户的所有阅读新闻文章。

 public interface NewsArticleRepository extends PagingAndSortingRepository{ Collection findByUserReadNewsArticlesReadAccountId(Long readAccountId); } 

这种方法效果很好。 但是,如何编写Spring Data JPA查询/方法来获取“未读新闻文章给用户”。 我试过的是以下内容。

 Collection findByUserReadNewsArticlesReadAccountIdNot(Long readAccountId); 

这个确实返回了其他用户已阅读的文章列表。 但我的要求是获取所有未读的新闻文章 。 我已经阅读了Spring Data JPA文档但未能提出更容易的灵魂。 我怎样才能克服这个问题? 或者我做错了什么?

您可以通过使用带有子查询的JPQL查询来实现结果:

 public interface NewsArticleRepository extends PagingAndSortingRepository { @Query("SELECT n FROM NewsArticle n WHERE n NOT IN " + "(SELECT ur.article FROM UserReadNewsArticle ur JOIN ur.account a WHERE a.id = :readAccountId)") Collection findByUserReadNewsArticlesReadAccountIdNotIn(@Param("readAccountId") Long readAccountId); } 

HTTP://本地主机:8080 / newsArticles /搜索/ findByUserReadNewsArticlesReadAccountIdNotIn readAccountId = 1

因此,首先从当前用户获取阅读清晰度,然后从整个文章列表中排除它们。

我不认为spring数据能够让你变得一样,因为子查询是绝对需要的。 如果我错了,有人可以纠正我。