SpringBoot整合PageHelper
导入坐标
导入分页插件的坐标。
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.10</version>
</dependency>
对分页插件配置
在配置类中对分页插件进行配置。
@Configuration
public class PageHelperConfig {
public PageHelper getPageHelper() {
PageHelper pageHelper = new PageHelper();
Properties properties = new Properties();
properties.setProperty("offsetAsPageNum","true");
properties.setProperty("rowBoundsWithCount","true");
properties.setProperty("reasonable","true");
//配置数据库方言
properties.setProperty("dialect","mysql");
pageHelper.setProperties(properties);
return pageHelper;
}
}
controller层代码
@Controller
@RequestMapping("/article")
public class ArticleController {
@Autowired
private ArticleService articleService;
/**
* 分页查询
* @param pageNum //当前是第几页
* @param pageSize //每页的数量
* @return
*/
@RequestMapping("/findByPage")
@ResponseBody
public String findByPage(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "5") int pageSize) {
//分页查询
PageInfo<Article> pageInfo = articleService.findByPage(pageNum, pageSize);
//将数据转换为json
String jsonString = JSON.toJSONString(pageInfo);
return jsonString;
}
}
service层代码
@Service
public class ArticleServiceImpl implements ArticleService {
@Autowired
private ArticleDao articleDao;
@Override
public PageInfo<Article> findByPage(int pageNum, int pageSize) {
//分页查询,会对紧跟着的第一个select方法进行分页查询,后面除非再次调用否则不会进行分页
PageHelper.startPage(pageNum, pageSize);
List<Article> articleList = articleDao.findAll();
int totalNum = articleDao.count();
PageInfo<Article> pageInfo = new PageInfo<>();
//设置当前页
pageInfo.setPageNum(pageNum);
//设置每页的数量
pageInfo.setPageSize(pageSize);
//设置当前页的数量
pageInfo.setSize(pageSize);
//设置结果集
pageInfo.setList(articleList);
return pageInfo;
}
}