SpringBoot MyBatis-Plus 分页查询 【SpringBoot系列7】

1,983 阅读2分钟

1 项目准备

官网地址:baomidou.com/

MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

在Mybatis-Plus的 BaseMapper 中,已经内置了2个支持分页的方法:

<P extends IPage<T>> P selectPage(P page, @Param("ew") Wrapper<T> queryWrapper);

<P extends IPage<Map<String, Object>>> P selectMapsPage(P page, @Param("ew") Wrapper<T> queryWrapper);

所以可以基于 BaseMapper 来实现基本的分页查询 当前来查询 用户分类数据 在这里插入图片描述

1 基于 BaseMapper 来实现分页查询


/**
 * <p>
 * 用户分类表 前端控制器
 * </p>
 *
 * @author 早起的年轻人
 * @since 2023-03-14
 */
@Api(tags="用户分类模块")
@RestController()
@RequestMapping("/auto/userCategory")
public class UserCategoryController {

    @Resource
    IUserCategoryService userCategoryService;
    @GetMapping(value="/findPage")
    @ApiOperation(value = "分页查询")
    public Object findPage(@RequestParam(required = false,defaultValue = "1") Integer index,
                           @RequestParam(required = false,defaultValue = "10") Integer pageSize) {
        Object page = userCategoryService.findPage(index, pageSize);
        return page;
    }
}

public interface IUserCategoryService extends IService<UserCategory> {

    Object findPage(Integer index, Integer pageSize);
}

/**
 * <p>
 * 用户分类表 服务实现类
 * </p>
 *
 * @author 早起的年轻人
 * @since 2023-03-14
 */
@Service("userCategoryService")
public class UserCategoryServiceImpl extends ServiceImpl<UserCategoryMapper, UserCategory> implements IUserCategoryService {

    @Resource
    UserCategoryMapper userCategoryMapper;
    @Override
    public Object findPage(Integer index, Integer pageSize){

        UserCategory userCategory = userCategoryMapper.selectById(1);
        Page<UserCategory> page = Page.of(index,pageSize);

        //queryWrapper组装查询where条件
        LambdaQueryWrapper<UserCategory> queryWrapper = new LambdaQueryWrapper<>();
        //查询条件 ID = 1 的数据
        queryWrapper.eq(UserCategory::getId,1);
        //发起查询
        userCategoryMapper.selectPage(page,queryWrapper);
        return page;
    }
}

@Mapper
public interface UserCategoryMapper extends BaseMapper<UserCategory> {

}

postman 执行访问

在这里插入图片描述

如果分页查询出现 total 为0的问题,可以添加一个分页插件自定义配置,比如我这里直接放到了启动类里面

@EnableFeignClients(basePackages = "com.biglead.feign.clients")
@SpringBootApplication
@MapperScan(basePackages = "com.biglead.admin.mapper")
public class AdminApplication {

	public static void main(String[] args) {
		SpringApplication.run(AdminApplication.class, args);
	}
	/**
	 * 分页插件
	 */
	@Bean
	public MybatisPlusInterceptor mybatisPlusInterceptor() {
		MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
		interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
		return interceptor;
	}
}

项目源码在这里 :gitee.com/android.lon…

有兴趣可以关注一下公众号:biglead

本文正在参加「金石计划」