四步教你SpringBoot+Mybatis-plus分页插件(简单实现)

MyBatis-Plus 分页插件---四步走

第一步:编写分页插件配置类

//Spring boot方式
@EnableTransactionManagement
@Configuration
@MapperScan("com.itheima.mapper")
public class MyBatisPlusConfig {
    /**
     * 分页插件
     * @return
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        //你的最大单页限制数量,默认 500 条,小于 0 如 -1 不受限制
        //paginationInterceptor.setLimit(2);
        return paginationInterceptor;
    }
}

第二步:编写Dao层代码

  • Mapper接口
public interface SsCompanyMapper extends BaseMapper<SsCompany> {//可以继承或者不继承BaseMapper
    /**
     * <p>
     * 查询 : 根据state状态查询用户列表,分页显示
     * 注意!!: 如果入参是有多个,需要加注解指定参数名才能在xml中取值
     * </p>
     *
     * @param page 分页对象,xml中可以从里面进行取值,传递参数 Page 即自动分页,必须放在第一位(你可以继承     * Page实现自己的分页对象)
     * @param state 状态,可以作为查询条件,可以不加
     * @return 分页对象
     */
    //IPage<User> selectPageVo(Page page, @Param("state") Integer state);
    IPage<SsCompany> selectPage(Page page);
}
  • Mapper.xml 等同于编写一个普通 list 查询,mybatis-plus 自动替你分页
  <select id="selectPage" resultType="com.itheima.domain.SsCompany">
      select * from ss_company
  </select>

注意:加不加where取决于你是否携带查询条件

第三步:调用分页方法

  • 接口
public interface SsCompanyService {
    IPage<SsCompany> selectPage(Page<SsCompany> page);
}
  • 实现类
@Service
@Transactional
public class SsCompanyServiceImpl implements SsCompanyService {

    @Autowired
    private SsCompanyMapper ssCompanyMapper;

    @Override
    public IPage<SsCompany> selectPage(Page<SsCompany> page) {
        // 不进行 count sql 优化,解决 MP 无法自动优化 SQL 问题,这时候你需要自己查询 count 部分
        // page.setOptimizeCountSql(false);
        // 当 total 为小于 0 或者设置 setSearchCount(false) 分页插件不会进行 count 查询
        // 要点!! 分页返回的对象与传入的对象是同一个
        return ssCompanyMapper.selectPage(page);
    }
}

第四步:编写Controller

@RestController
@RequestMapping("/company")
public class SsCompanyController {

    @Autowired
    private SsCompanyService ssCompanyService;

    @RequestMapping("/list")
    public IPage<SsCompany> list() {
        /**
         * Page(current,size)
         * current:当前页,long类型
         * size:每页显示的数量,long类型
         * 可参考其构造方法
         */
        IPage<SsCompany> iPage = ssCompanyService.selectPage(new Page<>(2l,3));
        return iPage;
    }
}

猜你喜欢

转载自www.cnblogs.com/guoyx/p/12095958.html
今日推荐