Mybatis
7、分页
思考:为什么要分页?
- 减少数据的处理量
7.1、使用Limit分页
语法:SELECT * FROM user LIMIT startIndex,pageSize;
SELECT * FROM user LIMIT 3; #[0,n]
使用Mybatis实现分页,核心SQL
接口
// 分页 List<User>getUserByLimit(Map<String,Object>map);
Mapper.xml
<!-- 分页实现查询--> <select id="getUserByLimit" parameterType="map" resultType="user"> select * from user limit #{startIndex},#{pageSize}; </select>
- 测试
推断:起始位置 = (当前页面 - 1 ) * 页面大小
@Test public void getUserByLimit(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); int currentPage = 1; //第几页 int pageSize = 2; //每页显示几个 HashMap<String, Object> map = new HashMap<>(); map.put("startIndex",(currentPage-1)*pageSize); map.put("pageSize",pageSize); List<User> userByLimit = mapper.getUserByLimit(map); for (User user : userByLimit) { System.out.println(user); } sqlSession.close(); }
7.2、RowBounds分页
不在使用SQL实现分页
接口
// 分页2 List<User>getUserByRowBounds();
mapper.xml
<select id="getUserByRowBounds" resultType="user"> select * from user; </select>
测试
@Test public void getUserByRowBounds(){ SqlSession sqlSession = MybatisUtil.getSqlSession(); // RowBounds 实现 RowBounds rowBounds = new RowBounds(0, 2); // 通过Jav代码层面实现分页 List<User> userList = sqlSession.selectList("getUserByRowBounds",null,rowBounds); for (User user : userList) { System.out.println(user); } sqlSession.close(); }
7.3、分页插件
了解即可,万一以后公司的架构师,说要使用,你需要知道他是什么东西!
MyBatis 分页插件 PageHelper官网:https://pagehelper.github.io/