gpt4 book ai didi

java - Spring Data JPA 查询中按子对象过滤时出错

转载 作者:行者123 更新时间:2023-11-30 06:47:16 25 4
gpt4 key购买 nike

我的代码结构如下所示。

文章:

@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<UserReadNewsArticle> 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<UserReadNewsArticle> userReadNewsArticles = new HashSet<>();

[Getters and Setters]
}

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

public interface NewsArticleRepository extends PagingAndSortingRepository<NewsArticle, Long>{

Collection<NewsArticle> findByUserReadNewsArticlesReadAccountId(Long readAccountId);

}

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

Collection<NewsArticle> findByUserReadNewsArticlesReadAccountIdNot(Long readAccountId);

这个确实返回其他用户已阅读的文章列表。但我的要求是获取所有未读的新闻文章。我已经经历过Spring Data JPA Documentation但未能想出一个更简单的灵魂。我怎样才能克服这个问题?还是我做错了什么?

最佳答案

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

public interface NewsArticleRepository extends PagingAndSortingRepository<NewsArticle, Long> {

@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<NewsArticle> findByUserReadNewsArticlesReadAccountIdNotIn(@Param("readAccountId") Long readAccountId);

}

http://localhost:8080/newsArticles/search/findByUserReadNewsArticlesReadAccountIdNotIn?readAccountId=1

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

我不认为 spring data 能够让你得到同样的结果,因为肯定需要子查询。如果我错了,有人可以纠正我。

关于java - Spring Data JPA 查询中按子对象过滤时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43487455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com