pagehelper是mybatis的一个分页插件,github地址:https://github.com/pagehelper/Mybatis-PageHelper,它支持mysql、oracle、db2、SqlLite等12种数据库的分页查询。
1、在pom.xml中引入pagehelper的依赖
<!--pagehelper引入 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.2.1</version>
</dependency>
2、spring.xml中SqlSessionFactoryBean,使用SqlMapConfig.xml配置文件
<!--5 mybatics sqlSessionFactory 工厂配置 -->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--引入数据源dataSource -->
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:SqlMapConfig.xml" />
</bean>
3、在SqlMapConfig.xml中配置plugin选项
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL等-->
<property name="dialect" value="mysql"/>
</plugin>
</plugins>
4、在业务代码中使用pagehelper分页插件
@Service
public class StudentService {
@Autowired
private StudentMapper studentMapper ;
/**
* 分页查询 使用pagehelper的mybatis插件包
* @param page
* @return
*/
public PageInfo findStudentList(Page page){
PageHelper.startPage(page.getPageNum(),page.getPageSize());
Map params=new HashMap();
//params.put(key, value)
List list =studentMapper.findStudentList(params);
PageInfo pageInfo =new PageInfo(list);
System.out.println("===============");
System.out.println(pageInfo);
return pageInfo;
}
}
调用PageHelper.startPage(page.getPageNum(),page.getPageSize()),可让在之后的第一个mapper查询方法使用上分页特性。
这意味着:当我们需要调用mapper的分页查询方法时,只需要在这之前执行下PageHelper.startPage(page.getPageNum(),page.getPageSize())即可。
PageHelper的源码如下:
/**
* Mybatis - 通用分页拦截器
* 项目地址 : http://git.oschina.net/free/Mybatis_PageHelper
*
* @author liuzh/abel533/isea533
* @version 5.0.0
*/
@SuppressWarnings("rawtypes")
@Intercepts(@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}))
public class PageHelper extends BasePageHelper implements Interceptor {
private final SqlUtil sqlUtil = new SqlUtil();
@Override
public Object intercept(Invocation invocation) throws Throwable {
return sqlUtil.intercept(invocation);
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
sqlUtil.setProperties(properties);
}
}
PageHelper使用ThreadLocal获取当前线程绑定变量,动态改变mapper的执行sql语句,从而实现自动分页的目的。
使用PageHelper返回的分页数据 例:
{
"pageNum": 0,
"pageSize": 10,
"size": 0,
"startRow": 0,
"endRow": 0,
"total": 0,//总条数
"pages": 0,
"list": [], //列表数据
"prePage": 0,
"nextPage": 0,
"isFirstPage": false,
"isLastPage": true,
"hasPreviousPage": false,
"hasNextPage": false,
"navigatePages": 8,
"navigatepageNums": [],
"navigateFirstPage": 0,
"navigateLastPage": 0,
"lastPage": 0,
"firstPage": 0
}


阅读排行


Copyright © 叮叮声的奶酪 版权所有
备案号:鄂ICP备17018671号-1