程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了在Spring Data JPA查询中按子对象过滤时出错大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决在Spring Data JPA查询中按子对象过滤时出错?

开发过程中遇到在Spring Data JPA查询中按子对象过滤时出错的问题如何解决?下面主要结合日常开发的经验,给出你关于在Spring Data JPA查询中按子对象过滤时出错的解决方法建议,希望对你解决在Spring Data JPA查询中按子对象过滤时出错有所启发或帮助;

您可以通过将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);

}
@H_801_6@

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

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

我认为spring数据无法使您满意,因为绝对需要子查询。如果我错了,有人可以纠正我

解决方法

我的代码结构如下所示。

文章:

@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]
}
@H_801_6@

用户阅读的文章:

@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]


}
@H_801_6@

帐户:

@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]
}
@H_801_6@

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

public interface NewsArticleRepository extends PagingAndSorTingRepository<NewsArticle,Long>{

    Collection<NewsArticle> findByUserReadNewsArticlesReadAccountId(Long readAccountId);

}
@H_801_6@

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

Collection<NewsArticle> findByUserReadNewsArticlesReadAccountIdNot(Long readAccountId);
@H_801_6@

这确实返回了由其他用户阅读的文章列表。但是我的 要求是获取所有未读的新闻文章 。我已经阅读过Spring Data
JPA文档,但没有想到更轻松的方法。我该如何克服这个问题?还是我做错了什么?

大佬总结

以上是大佬教程为你收集整理的在Spring Data JPA查询中按子对象过滤时出错全部内容,希望文章能够帮你解决在Spring Data JPA查询中按子对象过滤时出错所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。