原创

SpringBoot+Mybatis实现分页查询

前言

分页查询是在web开发中常用的一种技术,当某个页面查询返回的数据量较大时,为了提高性能和用户体验不能将所有数据一次性返回给过前端,这时候就需要用到分页查询了

PageHelper是一款开源的Mybatis第三方物理分页插件,spring boot项目中集成PageHelper插件非常简单,下面将为大家详细介绍; 插件地址:https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.md

1.引入依赖

在上一篇文章Mybatis 实现基本的增删改查 (基于Mybatis-generator插件方式)的基础上,在pom.xml中添加如下依赖:

        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.3</version>
        </dependency>

2.Mapper中接口

在EmployeeMapper.java中新增findByPaging接口,接口返回类型为Page

public interface EmployeeMapper {
    int deleteByPrimaryKey(Long id);

    int insert(Employee record);

    int insertSelective(Employee record);

    Employee selectByPrimaryKey(Long id);

    int updateByPrimaryKeySelective(Employee record);

    int updateByPrimaryKey(Employee record);

    Page<Employee> findByPaging();
}

3.修改XML文件

在EmployeeMapper.xml中添加上面接口对应Sql查询语句,可以看到使用插件的方式查询时,这里入参的类型为com.github.pagehelper.Page

  <select id="findByPaging" resultMap="BaseResultMap" parameterType="com.github.pagehelper.Page">
    select * from employee
    </select>

4.controller层调用接口

EmployeeController.java中新增findBypaging方法

    @GetMapping("findBypaging")
    public ResultMsg findByPaging(Integer pageNum, Integer pageSize){
        PageHelper.startPage(pageNum,pageSize);
        Page<Employee> data = employeeMapper.findByPaging();
        JSONObject result = new JSONObject();
        result.put("employees",data);
        //获取页面总数
        result.put("pages",data.getPages());
        //获取数据总数
        result.put("total",data.getTotal());
        return ResultMsg.getMsg(result);
    }

5.测试

编写一个测试用例,向数据库中批量插入200个员工数据

@RunWith(SpringRunner.class)
@SpringBootTest
public class HrefApplicationTests {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private IdWorker idWorker;
    public static String getRandomStr(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        int randomNum;
        char randomChar;
        Random random = new Random();
        // StringBuffer类型的可以append增加字符
        StringBuffer str = new StringBuffer();
        for (int i = 0; i < length; i++) {
            // 可生成[0,n)之间的整数,获得随机位置
            randomNum = random.nextInt(base.length());
            // 获得随机位置对应的字符
            randomChar = base.charAt(randomNum);
            // 组成一个随机字符串
            str.append(randomChar);
        }
        return str.toString();
    }
    Employee createRadomEmployee()
    {
        Employee employee = new Employee();
        employee.setAddress("北新街" + getRandomStr(5));
        employee.setAge("22");
        employee.setGender(new Short("1"));
        employee.setCreateTime(new Date());
        employee.setName(getRandomStr(10));
        employee.setId(idWorker.nextId());
        return employee;
    }
    @Test
    public void insertEmployees() {
        for(int i=0;i<402;i++)
        {
            employeeMapper.insert(createRadomEmployee());
        }
    }
}

执行后,看到测试数据已经建好

打开swagger,输入pageNum和pageSize,点击Try it out

返回结果如下:可以看到总数据为402,总页数为134,一共返回了3条数据

{
  "data": {
    "total": "402",
    "pages": 134,
    "employees": [
      {
        "address": "北新街4wf91",
        "age": "22",
        "createTime": 1558951333000,
        "deptId": 0,
        "gender": 0,
        "id": "317724116919799808",
        "name": "69wcpvii46"
      },
      {
        "address": "北新街8voe8",
        "age": "22",
        "createTime": 1558951333000,
        "deptId": 0,
        "gender": 0,
        "id": "317724117007880192",
        "name": "9sicl9xer4"
      },
      {
        "address": "北新街tbq90",
        "age": "22",
        "createTime": 1558951333000,
        "deptId": 0,
        "gender": 0,
        "id": "317724117309870080",
        "name": "u9zxm84sqo"
      }
    ]
  },
  "result": "SUCCESS",
  "resultCode": 200,
  "resultMsg": ""
}

总结

可以看到在spring boot中使用pageHealper插件进行分页查询很简单,包括如下3步:

  1. 导入插件依赖或jar包
  2. 在Mapper中添加接口,返回类型为Page<实体类型>,本例为Page
  3. 在xml中添加查询语句,入参的类型为com.github.pagehelper.Page

项目源码

原创

评论