Java jpa外連接查詢join案例詳解
1、IndexTagController.java
@GetMapping("/tags/{id}") public String types(@PageableDefault(size = 3,sort = {"updateTime"},direction = Sort.Direction.DESC)Pageable pageable, @PathVariable long id, Model model, HttpSession session){ //找到所有的標簽,並且按照標簽新聞量排序 List<Tag> tags = tagService.listTagTop(50); if(id == -1){ //得到最大數據量的分類 id = tags.get(0).getId(); } model.addAttribute("tags",tags); model.addAttribute("page",newsService.listNews(id,pageable)); model.addAttribute("activeId",id); session.setAttribute("query",""); return "tags"; }
newService.listNews(id,pgeable)中id為標簽的id,這個方法要做的就是查詢出標簽中包含id為參數id的所有新聞。
2、業務層代碼
NewService.java是一個接口,其中存在以下方法
//根據標簽Id查找符合條件的新聞 Page<News> listNews(long id,Pageable pageable);
NewServiceImpl.java為實現NewService接口的類,實現listNews方法
@Override public Page<News> listNews(long id, Pageable pageable) { return newsRepository.findAll(new Specification() { @Override public Predicate toPredicate(Root root, CriteriaQuery cq, CriteriaBuilder cb) { //外連接查詢 Join Join join =root.join("tags"); return cb.equal(join.get("id"),id); } },pageable); }
NewsRepository.java 繼承瞭JpaSpecificationExecutor
public interface NewsRepository extends JpaRepository<News,Long>, JpaSpecificationExecutor { @Query("select n from News n where n.recommend = true ") List<News> findTop(Pageable pageable); @Query("select n from News n where n.title like ?1 or n.content like ?1") Page<News> findByQuery(String query,Pageable pageable); @Query("select function('date_format',n.updateTime,'%Y') as year1 from News n group by year1 order by year1 desc ") List<String> findGroupYear(); @Query("select n from News n where function('date_format',n.updateTime,'%Y') = ?1 ") List<News> findByYear(String year); }
到此這篇關於Java jpa外連接查詢join案例詳解的文章就介紹到這瞭,更多相關Java jpa外連接查詢join內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- 詳解使用Spring Data repository進行數據層的訪問問題
- SpringBoot中JPA實現Sort排序的三種方式小結
- Spring Data JPA中 in 條件參數的傳遞方式
- spring data jpa @Query註解中delete語句報錯的解決
- 基於JPA的Repository使用詳解