Limit实现分页

分页

为什么要分页?

  • 减少数据的处理量

语法:

1
select * from user limit startIndex, pageSize;

使用SQL语句实现分页:

  1. 接口

    1
    2
    // 分页查询
    List<User> getUserByLimit(Map<String, Integer> map);
  2. Mapper.xml

    1
    2
    3
    <select id="getUserByLimit" parameterType="map" resultMap="UserMap">
    select * from mybatis.user limit #{startIndex}, #{pageSize};
    </select>
  3. 测试

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    @Test
    public void getUserByLimitTest(){
    SqlSession sqlSession = MybtisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);

    Map<String, Integer> map = new HashMap<>();
    map.put("startIndex", 1);
    map.put("pageSize", 2);

    List<User> users = mapper.getUserByLimit(map);

    for (User user : users) {
    System.out.println(user);
    }

    sqlSession.close();
    }
  4. 输出为:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    [org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Opening JDBC Connection
    [org.apache.ibatis.datasource.pooled.PooledDataSource]-Created connection 1631086936.
    [org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@61386958]
    [com.lxb.dao.UserMapper.getUserByLimit]-==> Preparing: select * from mybatis.user limit ?, ?;
    [com.lxb.dao.UserMapper.getUserByLimit]-==> Parameters: 1(Integer), 2(Integer)
    [com.lxb.dao.UserMapper.getUserByLimit]-<== Total: 2
    User{id=2, name='John', password='123456'}
    User{id=3, name='Jay', password='123456'}
    [org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@61386958]
    [org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@61386958]
    [org.apache.ibatis.datasource.pooled.PooledDataSource]-Returned connection 1631086936 to pool.

RowBounds分页

不推荐, 在Mapper.xml中查询整个表单, 然后测试时摘取, 不高效

分页插件

MyBatis分页插件 PageHelper

-------------本文结束感谢您的阅读-------------
可以请我喝杯奶茶吗