Java的新專案學成線上筆記-day3(一)
阿新 • • 發佈:2018-12-26
1 自定義條件查詢 1.1 需求分析
在頁面輸入查詢條件,查詢符合條件的頁面資訊。
查詢條件如下:
站點Id:精確匹配
模板Id:精確匹配
頁面別名:模糊匹配
...
1.2 服務端
1.2.1 Dao
使用 CmsPageRepository中的findAll(Example<S> var1, Pageable var2)方法實現,無需定義。
下邊測試findAll方法實現自定義條件查詢:
//自定義條件查詢測試 @Test public void testFindAll() { //條件匹配器 ExampleMatcher exampleMatcher = ExampleMatcher.matching(); exampleMatcher = exampleMatcher.withMatcher("pageAliase", ExampleMatcher.GenericPropertyMatchers.contains()); //頁面別名模糊查詢,需要自定義字串的匹配器實現模糊查詢 //ExampleMatcher.GenericPropertyMatchers.contains() 包含 //ExampleMatcher.GenericPropertyMatchers.startsWith()//開頭匹配 //條件值 CmsPage cmsPage = new CmsPage(); //站點ID cmsPage.setSiteId("5a751fab6abb5044e0d19ea1"); //模板ID cmsPage.setTemplateId("5a962c16b00ffc514038fafd"); // cmsPage.setPageAliase("分類導航"); //建立條件例項 Example<CmsPage> example = Example.of(cmsPage, exampleMatcher); Pageable pageable = new PageRequest(0, 10); Page<CmsPage> all = cmsPageRepository.findAll(example, pageable); System.out.println(all); }
1.2.2 Service
在PageService的findlist方法中增加自定義條件查詢程式碼
/** * 頁面列表分頁查詢 * @param page 當前頁碼 * @param size 頁面顯示個數 * @param queryPageRequest 查詢條件 * @return 頁面列表 */ public QueryResponseResult findList(int page,int size,QueryPageRequest queryPageRequest){ //條件匹配器 //頁面名稱模糊查詢,需要自定義字串的匹配器實現模糊查詢 ExampleMatcher exampleMatcher = ExampleMatcher.matching() .withMatcher("pageAliase", ExampleMatcher.GenericPropertyMatchers.contains()); //條件值 CmsPage cmsPage = new CmsPage(); //站點ID if(StringUtils.isNotEmpty(queryPageRequest.getSiteId())){ cmsPage.setSiteId(queryPageRequest.getSiteId()); } //頁面別名 if(StringUtils.isNotEmpty(queryPageRequest.getPageAliase())){ cmsPage.setPageAliase(queryPageRequest.getPageAliase()); } //建立條件例項 Example<CmsPage> example = Example.of(cmsPage, exampleMatcher); //頁碼 page = page‐1; //分頁物件 Pageable pageable = new PageRequest(page, size); //分頁查詢 Page<CmsPage> all = cmsPageRepository.findAll(example,pageable); QueryResult<CmsPage> cmsPageQueryResult = new QueryResult<CmsPage>(); cmsPageQueryResult.setList(all.getContent()); cmsPageQueryResult.setTotal(all.getTotalElements()); //返回結果 return new QueryResponseResult(CommonCode.SUCCESS,cmsPageQueryResult); }
1.2.3 Controller
無需修改 1.2.4 測試
使用SwaggerUI測試