我的代碼結構如下所示。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,但沒有提出一個更容易的靈魂。我怎樣才能克服這個問題?或者我做錯了什麼?
[jpa文檔](http://docs.spring.io/spring-data/jpa/docs/1.7.0.M1/reference/htmlsingle/#jpa.query-methods.query-creation)說你可以使用'不在'所以它似乎'收集 findNotInUserReadNewsArticlesByReadAccountId(長readAccountId);'會工作。 –
fiskra
@fiskra這將無法正常工作,我想從** NewsArticleRepository **中進行選擇,而不是UserReadNewsArticlesRepository。我已經和** NotIn **玩過了,但是還沒有能夠解決它 – SIRIM4N
除了你的問題..我想你可以刪除'readAccountId'和'readArticleId'這兩個字段,因爲你已經綁定了實體。 – KLHauser