使用分页是为了减少数据的处理量
1. 使用limit分页
#语法
select * from user limit startIndex,pageSize;
select * from user limit n; #[0,n]
使用Mybatis实现分页(本质还是SQL)
-
接口
//分页 List<User> getUserByLimit(Map<String,Integer> map);
-
Mapper.xml
<select id="getUserByLimit" parameterType="map" resultType="User"> select * from mybatis.user limit #{startIndex},#{pageSize}; </select>
-
测试
public void getUserByLimit(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); Map<String,Integer> map = new HashMap<String, Integer>(); map.put("startIndex",0); map.put("pageSize",2); List<User> userList = mapper.getUserByLimit(map); for (User user : userList) { System.out.println(user); } sqlSession.close(); }
2. RowBounds分页
不再使用SQL实现分页
-
接口
//RowBounds分页 List<User> getUserByRowBounds();
-
Mapper.xml
<!--RowBounds分页--> <select id="getUserByRowBounds" resultMap="UserMap"> select * from mybatis.user; </select>
-
测试
public void getUserByRowBounds(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); //RowBounds实现 RowBounds rowBounds = new RowBounds(0, 2); //通过Java代码层面实现分页 List<User> userList = sqlSession.selectList("com.lrm.dao.UserMapper.getUserByRowBounds",null,rowBounds); for (User user : userList) { System.out.println(user); } sqlSession.close(); }
3. PageHelper分页插件
-
导入依赖
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.2</version> </dependency>
-
配置到mybatis-config.xml配置文件
<plugins> <!-- com.github.pagehelper为PageHelper类所在包名 --> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <property name="properties" value="reasonable=true"/> </plugin> </plugins>
-
接口
//PageHelper分页 List<User> getUserByPagehelper();
-
mapper.xml
<!--Pagehelper分页--> <select id="getUserByPagehelper" resultType="User"> select * from mybatis.user </select>
-
测试类
public void getUserByPagehelper(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); PageHelper.startPage(0,2); List<User> userList = mapper.getUserByPagehelper(); for (User user : userList) { System.out.println(user); } sqlSession.close(); }