一、PageHelper使用套路
1.Maven引入PageHelper与jsqlparser
<!--PageHelper核心依赖-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.8</version>
</dependency>
<!--jsqlparser SQL文本解析器-->
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>0.9.5</version>
</dependency>
2.mybatis-config.xml增加Plugin配置
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!--识别数据库类型,可以省略不写,进行自动识别-->
<property name="helperDialect" value="mysql"/>
<!--分页合理化-->
<property name="reasonable" value="true"/>
</plugin>
</plugins>
3.代码中使用PageHelper.startPage()自动分页
@Test
public void testDynamicSQL(){
SqlSession session = null;
//openSession创建一个新的SqlSession对象,SqlSession提供了增删改查的方法调用
try {
session = sqlSessionFactory.openSession();
Map param = new HashMap();
param.put("categoryId", 44);
param.put("currentPrice", 500);
/*startPage方法会自动将下一次查询进行分页*/
PageHelper.startPage(2, 10);
List<Goods> list = session.selectList("goods.dynamicSQL" , param);
for (Goods goods : list) {
System.out.println(goods.getTitle() + "-" + goods.getCurrentPrice());
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (session != null) {
//将Connection归还到连接池供其他Session重用
session.close();
}
}
}
网友评论