在做協(xié)會網(wǎng)站時佩脊,有一個API症昏,是可以通過標簽查詢對應(yīng)的文章随闽。所以我在文章的 DAO , IArticleDAO 里有個函數(shù)
@Query("select a from ArticleTag a where a.tag in ?1 and a.article.status in ?2")
Page<Article> findArticleByTags(List<Tag> tags, String[] status, Pageable pageable);
但是到我上層 Services 查詢回來的結(jié)果返回給 Controller 之后,發(fā)現(xiàn)返回的 Page<Article> 里面居然裝的是 ArticleTag 對象肝谭。掘宪。。我懵了分苇。查了好久發(fā)現(xiàn)原來是查詢語句寫錯了添诉,應(yīng)該 select a.article
才對,于是改成
@Query("select a.article from ArticleTag a where a.tag in ?1 and a.article.status in ?2")
但是返回的還是 ArticleTag 医寿。栏赴。。
于是我又猜了一下靖秩,可能是不能這么查詢须眷?試了一下改成以 ArticleTag.article 為查詢對象
@Query("select a from ArticleTag.article a where ArticleTag.tag in ?1 and a.status in ?2")
于是出現(xiàn)了如下錯誤直接導致 Services 沒法加載
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: ArticleTag.article is not mapped [select a from ArticleTag.article a where ArticleTag.tag in ?1 and a.status in ?2]
好吧竖瘾。。花颗。捕传。上網(wǎng)再查一下 JPA 查詢的文章,我發(fā)現(xiàn)了這篇 JPA JPQL 查詢扩劝、排序.....(轉(zhuǎn))(那個“轉(zhuǎn)”字我看得很不順眼庸论。。)棒呛,里面的 關(guān)聯(lián)(join) 部分 提到
在默認的查詢中聂示, Entity 中的集合屬性默認不會被關(guān)聯(lián),集合屬性默認是延遲加載 ( lazy-load ) 簇秒。
然后重新寫了之后就變成現(xiàn)在這個了
@Query("select at.article from ArticleTag at join at.article where at.tag in ?1 and at.article.status in ?2 order by at.article.createDate")
繼續(xù)使用 PageRequest 來指定通過文章的某個字段排序也是可以的鱼喉。刪掉 order by ,改在 PageRequest 里使用 article.createDate 即可趋观。因為 JPA 查詢實際上會把 PageRequest 里的排序拼接在 JQL 語句里面扛禽。實際發(fā)出去的 JPA 是跟上面在 Query 注解里的查詢語句是一樣的。