1. 引入依赖
<!-- 分页插件依赖 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>4.1.0</version> </dependency>
2. 新建配置类(也可以使用 application.properties)
import com.github.pagehelper.PageHelper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Properties; /** * mybatis分页插件配置 */ @Configuration public class MyBatisConfig { @Bean public PageHelper pageHelper(){ PageHelper pageHelper = new PageHelper(); Properties p = new Properties(); // 设置为true时,会将RowBounds第一个参数offset当成pageNum页码使用 p.setProperty("offsetAsPageNum","true"); //设置为true时,使用RowBounds分页会进行count查询 p.setProperty("rowBoundsWithCount","true"); p.setProperty("reasonable","true"); pageHelper.setProperties(p); return pageHelper; } }
3. 使用 PageHelper
/** * 分页接口 * @param page 当前第几页,默认是第一页 * @param size 每页显示几条 * @return */ @GetMapping("page") public Object pageVideo(@RequestParam(value = "page",defaultValue = "1")int page, @RequestParam(value = "size",defaultValue = "10")int size){ PageHelper.startPage(page,size); List<Video> list = videoService.findAll(); PageInfo<Video> pageInfo = new PageInfo<>(list); Map<String,Object> data = new HashMap<>(); data.put("total_size",pageInfo.getTotal());//总条数 data.put("total_page",pageInfo.getPages());//总页数 data.put("current_page",page);//当前页 data.put("data",pageInfo.getList());//数据 return data; }