首先引入jar包:
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> </dependency>
然后在mybatis配置文件中配置:
SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <plugins> <!-- com.github.pagehelper 为 PageHelper 类所在包名 --> <plugin interceptor="com.github.pagehelper.PageHelper"> <!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL 六种数据库--> <property name="dialect" value="mysql"/> </plugin> </plugins> </configuration>
代码中使用:
Service
package com.pinyougou.sellergoods.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import com.alibaba.dubbo.config.annotation.Service; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.pinyougou.mapper.TbBrandMapper; import com.pinyougou.pojo.TbBrand; import com.pinyougou.sellergoods.service.BrandService; import entity.PageResult; @Service public class BrandServiceImpl implements BrandService { @Autowired private TbBrandMapper brandMapper; @Override public PageResult findPage(int pageNum, int pageSize) { //声明下面的查询要使用分页插件 PageHelper.startPage(pageNum, pageSize); //查询方法一:直接将查询结果强转成 page对象 Page<TbBrand> page = (Page<TbBrand>) brandMapper.selectByExample(null); return new PageResult(page.getTotal(), page.getResult()); //查询方法二:将查询结果封装成pageInfo对象 // List<TbBrand> list = brandMapper.selectByExample(null); // PageInfo<TbBrand> pageInfo = new PageInfo<>(list); // return new PageResult(pageInfo.getTotal(), pageInfo.getList()); } }
Controller:
package com.pinyougou.manager.controller; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipOutputStream; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.alibaba.dubbo.config.annotation.Reference; import com.pinyougou.pojo.TbBrand; import com.pinyougou.sellergoods.service.BrandService; import entity.PageResult; @RestController @RequestMapping("/brand") public class BrandController { @Reference private BrandService brandService; /** *<p>Description: 分页查询<p> * @date 2018年11月19日 * @param page 当前页码 * @param size 每页记录条数 * @return */ @RequestMapping("/findPage") public PageResult findPage(int page,int size) { return brandService.findPage(page,size); }
测试: