文章目录
- 1、Limit实现分页
- 2、RowBounds分页(不建议使用)
- 3、MyBatis分页插件PageHelper(了解即可)
1、Limit实现分页
-
sql语句
SELECT * from user limit startIndex,pageSize
-
简单示例:
-
user表
-
查询一:从第一行数据【 startIndex:0】开始,查询两行【pageSize:2】数据
SELECT * from user limit 0,2;
-
查询二:从第三行数据【 startIndex:2】开始,查询两行【pageSize:2】数据
SELECT * from user limit 2,2;
-
查询三:只有一个参数表示从第一行数据开始,查询三行【pageSize:3】数据
SELECT * from user limit 3;
-
-
使用Mybatis实现分页,核心SQL
-
接口
public interface UserMapper {//分页List<User> getUserByLimit(Map<String,Integer> map); }
-
Mapper.xml
<!--分页--> <select id="getUserByLimit" parameterType="map" resultType="包名.User">select * from user limit #{startIndex},#{pageSize}; </select>
-
测试
public class UserMapperTest {@Testpublic void getUserByLimit() {SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);HashMap<String, Integer> map = new HashMap<>();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实现分页,通过java代码层面实现分页
-
接口
//分页2:RowBounds List<User> getUserByRowBounds();
-
Mapper.xml
<!--分页:RowBounds--> <select id="getUserByRowBounds" resultMap="UserMap">select * from user </select>
-
测试
@Test //分页2:RowBounds public void getUserByRowBounds(){SqlSession sqlSession = MybatisUtils.getSqlSession();//RowBounds实现RowBounds rowBounds = new RowBounds(0, 2);//通过java代码层面实现分页List<User> userList = sqlSession.selectList("com.ping.dao.UserMapper.getUserByRowBounds",null,rowBounds);for (User user : userList) {System.out.println(user);}sqlSession.close(); }
-
测试结果
-
3、MyBatis分页插件PageHelper(了解即可)
详细文档:https://pagehelper.github.io/