2017-04-19 91 views
1

我的代碼結構如下所示。Spring Data中的子對象過濾錯誤JPA查詢

文章:

@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,但沒有提出一個更容易的靈魂。我怎樣才能克服這個問題?或者我做錯了什麼?

+0

[jpa文檔](http://docs.spring.io/spring-data/jpa/docs/1.7.0.M1/reference/htmlsingle/#jpa.query-methods.query-creation)說你可以使用'不在'所以它似乎'收集 findNotInUserReadNewsArticlesByReadAccountId(長readAccountId);'會工作。 – fiskra

+0

@fiskra這將無法正常工作,我想從** NewsArticleRepository **中進行選擇,而不是UserReadNewsArticlesRepository。我已經和** NotIn **玩過了,但是還沒有能夠解決它 – SIRIM4N

+0

除了你的問題..我想你可以刪除'readAccountId'和'readArticleId'這兩個字段,因爲你已經綁定了實體。 – KLHauser

回答

1

您可以通過使用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

因此,首先從當前用戶獲得讀articels,然後從整篇文章列表exlude他們。

我不認爲彈簧數據能夠讓你一樣,因爲子查詢是必要的。如果我錯了,有人可以糾正我。

+0

我試過了。雖然 – SIRIM4N

+0

我無法得到它的工作,我添加了一些更多的信息。也許這有幫助。如果沒有,發生了什麼? – KLHauser

+0

它確實工作。驚人。我以前嘗試過的時候肯定犯了錯誤。非常感謝。 – SIRIM4N