本文章前提是已经搭建好spring boot 和 mybatis框架,以下是分页过程
1、引入Pagehelper依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.3</version>
</dependency>
2、新建数据库表,我的测试表较为简单,只有三个参数:
3、在spring boot启动类配置pagehelper,我配置在main方法下面
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
@Bean
PageHelper pageHelper(){
//分页插件
PageHelper pageHelper = new PageHelper();
Properties properties = new Properties();
properties.setProperty("reasonable", "true");
properties.setProperty("supportMethodsArguments", "true");
properties.setProperty("returnPageInfo", "check");
properties.setProperty("params", "count=countSql");
pageHelper.setProperties(properties);
//添加插件
new SqlSessionFactoryBean().setPlugins(new Interceptor[]{pageHelper});
return pageHelper;
}
4、mapper文件实现调用数据库数据,返回结果类型为实体类类型:
<select id="getAll" resultType="com.light.spring.Entity.Department">
select id,name,descr from department
</select>
5、在dao层建立接口文件,并在service层实现:
//dao层
@Mapper
@Component
public interface DepartmentMapper {
//使用list数组存值
public List<Department> getAll();
}
//service实现接口
@Service
public class DepartmentServiceImpl implements DepartmentService{
@Autowired
private DepartmentMapper departmentMapper;
@Override
public List<Department> getAll(){
return this.departmentMapper.getAll();
}
}
6、controller层调用Pagehelper实现数据分页:
@PostMapping ("/helloworld")
public PageInfo<Department> hello2(Integer PageNum,Integer PageSize){
PageHelper.startPage(PageNum,PageSize);//第一个参数是当前页码,第二个参数是显示的列数
List<Department> list=departmentServiceImpl.getAll();
for (Department i: list
) {
System.out.println(i);
}
PageInfo<Department> pageInfo = new PageInfo<Department>(list);
return pageInfo;
}
7、测试:为了实现大量数据,用for循环写入多个数据到数据库,代码如下:
Department department=new Department();
for (int i=0;i<100;i++){
String name="Mapper"+i;
String descr="Descr"+i*10;
department.setName(name);
department.setDescr(descr);
this.departmentServiceImpl.insert(department);
}
数据库数据如图:
接下来调用分页接口:
使用swagger测试,参数如下:
得到结果,成功:
{
"endRow": 24,
"firstPage": 4,
"hasNextPage": true,
"hasPreviousPage": true,
"isFirstPage": false,
"isLastPage": false,
"lastPage": 11,
"list": [
{
"descr": "Descr210",
"id": 22,
"name": "Mapper21"
},
{
"descr": "Descr220",
"id": 23,
"name": "Mapper22"
},
{
"descr": "Descr230",
"id": 24,
"name": "Mapper23"
}
],
"navigatePages": 8,
"navigatepageNums": [
4,
5,
6,
7,
8,
9,
10,
11
],
"nextPage": 9,
"pageNum": 8,
"pageSize": 3,
"pages": 34,
"prePage": 7,
"size": 3,
"startRow": 22,
"total": 100
}
分页数据渲染到前端页面:https://blog.csdn.net/qq_39112803/article/details/85267083