前言:Mybatis是一个面向关系的轻量级框架,
Hiberbate是基于ORM(对象关系数据库映射)面向对象的框架,JPA系列相似(本质就是里面有很多类,每个类都能有功能,最后集成为一个框架)
为什么要分页
减少数据的处理量
运用sql(limit)语句实现分页
select * from mybatis.user limit 2,2;
一,使用Mybatis实现分页,核心SQL(面向关系)
接口
//利用limit实现分页 List<User> getUserByLimit(Map<String,Integer> map);
Mapper.xml
<!--//分页--> <select id="getUserByLimit" parameterType="map" resultMap="userMap"> select * from mybatis.user limit #{startIndex},#{pageSize}; </select>c
测试
@Test public void limitTest(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); HashMap<String, Integer> map = new HashMap<String, Integer>(); map.put("startIndex",2); map.put("pageSize",2); List<User> userList = mapper.getUserByLimit(map); for (User user : userList) { System.out.println(user); } sqlSession.close(); }
二,RowBounds实现分页(本质,在sql层面将所有数据查出来,最后在Java层面利用RowBounds对象,实现分页)
接口
//利用limit实现分页(基于java层面实现) List<User> getUserByRowBounds();
mapper.xml
<!--//分页2--> <select id="getUserByRowBounds" resultMap="userMap"> select * from mybatis.user; </select>
测试
@Test public void limitTest2(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); //RowBounds实现分页 RowBounds rowBounds = new RowBounds(1,2); List<Object> list = sqlSession.selectList("com.king.dao.UserMapper.getUserByRowBounds", null, rowBounds); for (Object user : list) { System.out.println(user); } sqlSession.close(); }
插件分页可以看官方文档逐步实现,原理与RowBounds相似