Mybatis-PageHelper分页处理插件

工具&mybatis _ Mybatis-PageHelper分页处理插件

支持 MyBatis 3.1.0+

这个只是简单入门集成,更加详细的使用推荐查看官方的文档

https://github.com/pagehelper/Mybatis-PageHelper/blob/master/README_zh.md

集成pom.xml依赖添加

1
2
3
4
5
6
7
<!-- mybatis pager -->

<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.0</version>
</dependency>

修改spring配置文件 bean — sqlSessionFactory

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath*:mappers/*Mapper.xml"></property>

<!-- 分页插件 -->
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageHelper">
<property name="properties">
<!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库-->
<value>
dialect=mysql
</value>
</property>
</bean>
</array>
</property>

</bean>

配置即完成了。

coding

简单的分页实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class Test {

ApplicationContext cxt = null;

@Before
public void init(){
cxt = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
}
@After
public void after(){
cxt = null;
}

@org.junit.Test
public void test1(){
List<EntryExitRecord> entryExitRecordList = new ArrayList<EntryExitRecord>();
EntryExitRecordService entryExitRecordService = (EntryExitRecordService)cxt.getBean("entryExitRecordServiceImpl");
// 当前页大小
int pageNum = 1;
// 每页大小
int pageSize = 10;
PageHelper.startPage(pageNum,pageSize);
entryExitRecordList = entryExitRecordService.getEntryExitRecord();
int size = entryExitRecords.size();
for (EntryExitRecord record : entryExitRecords){
System.out.println(record.getId()+" "+record.getPersonName());
}
PageInfo pageResult = new PageInfo(entryExitRecords);
System.out.println(pageResult);
}
}

重要提示

PageHelper.startPage方法重要提示

只有紧跟在PageHelper.startPage方法后的第一个Mybatis的查询(Select)方法会被分页。

请不要配置多个分页插件

请不要在系统中配置多个分页插件(使用Spring时,mybatis-config.xmlSpring<bean>配置方式,请选择其中一种,不要同时配置多个分页插件)!

分页插件不支持带有for update语句的分页

对于带有for update的sql,会抛出运行时异常,对于这样的sql建议手动分页,毕竟这样的sql需要重视。

分页插件不支持嵌套结果映射

由于嵌套结果方式会导致结果集被折叠,因此分页查询的结果在折叠后总数会减少,所以无法保证分页结果数量正确。

坚持原创技术分享,您的支持将鼓励我继续创作!