1. 引入依賴
compile('com.github.pagehelper:pagehelper-spring-boot-starter:1.2.10')
2. 将分頁邏輯單獨拎出來實作
public class PageUtility {
public static PageSerializable<?> search(MyPage myPage, Object repository, Method method, Object... args)
throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Page<?> page = PageHelper.startPage(myPage.getNumber(), myPage.getSize(), myPage.getOrderBy());
List<?> list = (List<?>) method.invoke(repository, args);
PageSerializable<?> result = new PageSerializable<>(list);
result.setTotal(page.getTotal());
return result;
}
}
3. 實作Service
public MyResponse searchByType(String type, MyPage myPage) throws NoSuchMethodException, SecurityException,
IllegalAccessException, IllegalArgumentException, InvocationTargetException {
MyResponse response = new MyResponse();
Method method = materialRepository.getClass().getMethod("searchByType", String.class);
response.setData(PageUtility.search(myPage, materialRepository, method, type));
response.setData(materialRepository.searchByType(type));
return response;
}
materialRepository.searchByType(String type) 傳回類型是List<Material>
4. 實作Controller
@ApiOperation(value = "Material search by type", notes = "No information")
@PostMapping(path = "/search-by-type")
public MyResponse searchByType(
@ApiParam(value = "Material type", required = true) @RequestParam("type") String type,
@ApiParam(value = "MyPage info in json format", required = true) @RequestBody MyPage myPage)
throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,
InvocationTargetException {
return materialService.searchByType(type, myPage);
}
That's all. Simple.