SELECT * FROM school.`user` LIMIT startIndex,pageSize
SELECT * FROM school.`user` LIMIT 2 -- 0,2
SELECT * FROM school.`user` LIMIT 2,2 -- startIndex从0开始
使用mybatis实现分页步骤,核心sql
接口
public List selectUserMap(Map map);
@Test
public void testMybatis02(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap map = new HashMap<>();
map.put("startIndex",1);
map.put("pageSize",2);
List users = mapper.selectUserMap(map);
System.out.println(users.size());
users.forEach(val->{
logger.debug(val.toString());
});
sqlSession.close();
}
protected static final ThreadLocal LOCAL_PAGE = new ThreadLocal();
/**
* 设置 Page 参数
*
* @param page
*/
protected static void setLocalPage(Page page) {
LOCAL_PAGE.set(page);
}
/**
* 开始分页
*
* @param pageNum 页码
* @param pageSize 每页显示数量
* @param count 是否进行count查询
* @param reasonable 分页合理化,null时用默认配置
* @param pageSizeZero true且pageSize=0时返回全部结果,false时分页,null时用默认配置
*/
public static Page startPage(int pageNum, int pageSize, boolean count, Boolean reasonable, Boolean pageSizeZero) {
Page page = new Page(pageNum, pageSize, count);
page.setReasonable(reasonable);
page.setPageSizeZero(pageSizeZero);
//当已经执行过orderBy的时候
Page oldPage = getLocalPage();
if (oldPage != null && oldPage.isOrderByOnly()) {
page.setOrderBy(oldPage.getOrderBy());
}
setLocalPage(page);
return page;
}
com.github.pagehelper
pagehelper
5.3.0
在mybatis-config.xml核心配置文件中配置plugins
注意mybatis-config.xml各元素顺序
The content of element type “configuration” must match "(properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,reflectorFactory?,plugins?,environments?,databaseIdProvider?,mappers?)
List selectUserPagehelper();
@Test
public void testMybatis04(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
/**
* 开始分页
*
* @param pageNum 页码
* @param pageSize 每页显示数量
*/
PageHelper.startPage(2,2);
List users = mapper.selectUserPagehelper();
PageInfo userPageInfo = new PageInfo<>(users);
//return userPageInfo;
System.out.println(userPageInfo.getPageSize());
System.out.println(users.size());
users.forEach(val->{
logger.debug(val.toString());
});
sqlSession.close();
}
List selectUserRowBounds();
@Test
public void testMybatis05(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
//RowBounds创建
RowBounds rowBounds = new RowBounds(1,2);
//java代码层面分页
List user = sqlSession.selectList("com.zk.dao.UserMapper.selectUserRowBounds",null,rowBounds);
System.out.println(user.size());
user.forEach(val->{
logger.debug(val.toString());
});
sqlSession.close();
}