分页
1.使用Limit分页
语法:SELECT * from user limit startIndex,pageSize;
SELECT * from user limit 3; #[0,n]
1.编写接口
//分页查询
List<User> getUserByLimit(Map<String,Integer> map);
2.mapper中配置
<select id="getUserByLimit" parameterType="map" resultType="User">
select * from mybatis.user limit #{startIndex},#{pageSize}
</select>
3.测试
@Test
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> users = mapper.getUserByLimit(map);
for (User user : users) {
System.out.println(user);
}
sqlSession.close();
}
2. RowBounds分页
-
编写接口
//分页2 List<User> getUserByRowBounds();
-
mapper.xml
<!--分页2--> <select id="getUserByRowBounds" resultType="User"> select * from mybatis.user </select>
-
测试
@Test public void getUserByRowBounds(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); //RowBounds实现 RowBounds rowBounds = new RowBounds(0, 2); //通过Java代码层面实现分页 List<User> userList = sqlSession.selectList("com.kuang.dao.UserMapper.getUserByRowBounds",null,rowBounds); for (User user : userList) { System.out.println(user); } sqlSession.close(); }
3. 第三方插件PageHelper
官网:https://pagehelper.github.io/
无论用什么方法,底层都是sql语句limit实现