spring boot 中利用 jpa 实现后台分页
spring boot 中利用 jpa 实现后台分页
要实现的效果是每页显示 10 条数据,数据源为 mongodb 中的数据
1 个解决方案
核心是利用 Pageable 这个接口,其中 PageRequest 为实现了这个接口的类。
注意:导入 Pageable 包的时候不要导入错了,应为 org.springframework.data.domain.Pageable
最基本的 PageRequest 的构造方法为 PageRequest(int,int),分别为起始页数 (从 0 开始) 以及每页最大条数。
代码:
jpa:
public interface JobRepository extends MongoRepository<JobInfo,String> { }
Controller:
/**
* @author jianghui
* @date 2018/5/26 下午 4:49
*/
@Controller
public class JobController {
@Autowired
private JobBusinessImpl jobBusinessImpl;
@GetMapping("/{page}")public String test(@PathVariable("page") int page, Model model){model.addAttribute("jobs",jobBusinessImpl.queryJobInfoByPage(page));
return "home";
}
}
Business:
@Service
public class JobBusinessImpl implements JobBusiness{
@Autowired
private JobRepository jobRepository;
@Override
public List<JobInfo> queryJobInfoByPage(int page){Pageable pageable = new PageRequest(page,10);
List<JobInfo> jobs = jobRepository.findAll(pageable).getContent();
return jobs;
}
}