Mybatis-plus的分页插件的使用

1: 创建MybatisPlus配置类

/**
 * MybatisPlus配置类
 *
 * @version 1.0
 * @date 2022/06/21 10:30:08
 */
@Configuration
public class MybatisPlusConfig {

    /**
     * 配置分页插件
     * @return com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor
     * @date 2022/6/21 10:31:43
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        //添加分页插件
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return mybatisPlusInterceptor;
    }
}

2: Mapper接口

/**
 * User实体类Mapper接口
 * BaseMapper是MyBatis-Plus提供的模板mapper,其中包含了基本的CRUD方法,泛型为操作的实体类型
 *
 * @version 1.0
 * @date 2022/06/19 00:29:38
 */
@Mapper
public interface UserMapper extends BaseMapper {
}

3: Controller测试接口

    /**
     * 分页获取数据接口
     *
     * @param page 页码
     * @param pageSize 每页记录数
     * @return com.xyz.mybatisplus.util.AjaxResult
     * @date 2022/6/21 10:42:37
     */
    @GetMapping(value = "/getPageData/{page}/{pageSize}")
    public AjaxResult getPageData(@PathVariable("page") Integer page, @PathVariable("pageSize") Integer pageSize) {
        page = page == null ? 1 : page;
        pageSize = pageSize == null ? 1 : pageSize;
        try {
            Map map = new HashMap<>();
            Page page1 = new Page<>(page, pageSize);
            Page userPage = userMapper.selectPage(page1, null);
            map.put("是否存在下一页", userPage.hasNext());
            map.put("是否存在上一页", userPage.hasPrevious());
            map.put("总页数", userPage.getPages());
            map.put("总记录数", userPage.getTotal());
            map.put("当前页", userPage.getCurrent());
            map.put("每页记录数", userPage.getSize());
            List records = userPage.getRecords();
            map.put("当前页数据", records);
            return AjaxResult.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("Mapper接口-分页获取数据出现异常:{}", e.getMessage());
            return AjaxResult.error(e.getMessage());
        }
    }

接口返回结果

接口地址:http://localhost:9001/test/getPageData/1/3

{
	"msg": "操作成功",
	"code": 200,
	"data": {
		"是否存在下一页": true,
		"是否存在上一页": false,
		"当前页数据": [
			{
				"id": 2,
				"name": "Jack",
				"age": 20,
				"email": "[email protected]",
				"isDelete": 0,
				"education": null
			},
			{
				"id": 3,
				"name": "秦羽",
				"age": 26,
				"email": "[email protected]",
				"isDelete": 0,
				"education": null
			},
			{
				"id": 4,
				"name": "Sandy",
				"age": 21,
				"email": "[email protected]",
				"isDelete": 0,
				"education": null
			}
		],
		"总记录数": 50,
		"每页记录数": 3,
		"总页数": 17,
		"当前页": 1
	}
}

你可能感兴趣的:(java,mysql,mybatis-plus)