创建MybatisPlusConfig配置类,配置分页插件
package com.example.pagetest.conf;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* MybatisPlus配置类
*/
@Configuration
public class MyBatisPlusConfig {
/**
* MybatisPlus拦截器添加分页插件
*
* @return
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
}
@GetMapping("/list/page")
public Page listPage(Integer sex, Long pageCurrent, Long pageSize) {
log.info("current: {}, pageSize: {}", pageCurrent, pageSize);
// 构造查询条件
QueryWrapper queryWrapper = new QueryWrapper<>();
queryWrapper.eq("sex", sex);
// 创建分页对象
Page<User> page = new Page<>(pageCurrent, pageSize);
// 调用IService接口的page方法,执行分页查询
Page<User> userPage = userService.page(page, queryWrapper);
return userPage;
}
{
????"records":?[
????????{
????????????"id":?1,
????????????"name":?"张三",
????????????"age":?18,
????????????"sex":?0,
????????????"createTime":?null,
????????????"createBy":?null
????????},
????????{
????????????"id":?2,
????????????"name":?"李四",
????????????"age":?19,
????????????"sex":?0,
????????????"createTime":?null,
????????????"createBy":?null
????????}
????],
????"total":?4,
????"size":?2,
????"current":?1,
????"orders":?[],
????"optimizeCountSql":?true,
????"searchCount":?true,
????"countId":?null,
????"maxLimit":?null,
????"pages":?2
}
(1)mapper接口
@Mapper
public interface UserMapper extends BaseMapper<User> {
Page<User> selectListPage(Page page, @Param("sex") Integer sex);
}
(2)自定义SQL
<select id="selectListPage" resultMap="BaseResultMap">
select
id, name, age, sex, create_time, create_by
from user
where sex = #{sex}
</select>
(3)代码
@Override
public Page queryListPageBySQl(Integer sex, Long pageCurrent, Long pageSize) {
// 创建分页对象
Page<User> page = new Page<>(pageCurrent, pageSize);
Page<User> userPage = userMapper.selectListPage(page, sex);
return userPage;
}