文章目录
- 一、分页的几种方式
- 1、使用关键字实现分页(limit)
- 2、通过 RowBounds 类实现分页查询
- 3、使用分页插件实现分页
分页的作用:在进行查询时如果数据量庞大的话会造成大量的内存压力,让程序卡顿。这时候使用分页减少数据的处理量便可以很好的解决此问题。
一、分页的几种方式
1、使用关键字实现分页(limit)
- 语法:SELECT * from user limit startIndex,pageSize
分页代码示例:
-
mapper 接口
// 分页查询 List<User> queryLimit(Map<String,Integer> map);
-
mapper.xml
<select id="queryLimit" parameterType="map" resultType="com.demo_01.entity.User"> select * from user limit #{startIndex}, #{pageSize} </select>
-
queryLimitMain 测试类
// 分页查询 public class queryLimitMain { @Test public void test() throws IOException { InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); try { IUserMapper mapper = sqlSession.getMapper(IUserMapper.class); Map<String,Integer> map = new HashMap<>(); map.put("startIndex",0); map.put("pageSize",2); List<User> list = mapper.queryLimit(map); for(User user:list){ String info= String.format("id:%s,用户名:%s,密码:%s",user.getId(),user.getName(),user.getPwd() ); System.out.println(info); } }finally{ sqlSession.close(); } } }
-
运行结果 :
2、通过 RowBounds 类实现分页查询
- 使用 RowBounds 类的构造方法实现分页
分页代码示例:
-
mapper 接口
// 分页查询 List<User> queryRowBounds(RowBounds rowBounds);
-
mapper.xml
<select id="queryRowBounds" resultType="com.demo_01.entity.User"> select * from user </select>
-
queryRowBoundsMain 测试类
// 分页查询 public class queryRowBoundsMain { @Test public void test() throws IOException { InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); try { IUserMapper mapper = sqlSession.getMapper(IUserMapper.class); RowBounds rowBounds = new RowBounds(0,2); List<User> list = mapper.queryRowBounds(rowBounds); for(User user:list){ String info= String.format("id:%s,用户名:%s,密码:%s",user.getId(),user.getName(),user.getPwd() ); System.out.println(info); } }finally{ sqlSession.close(); } } }
-
运行结果:
–