mybatis pagehelper分页插件使用

使用过mybatis的人都知道,mybatis本身就很小且简单,sql写在xml里,统一管理和优化。缺点当然也有,比如我们使用过程中,要使用到分页,如果用最原始的方式的话,1.查询分页数据,2.获取分页长度,也就是说要使用到两个方法才能完成分页。有没有更更好的分页方式的,pagehelper分页插件因此而诞生,他的原理是利用mybatis拦截器,在查询数据库的时候,拦截下SQL,然后进行修改,从而实现分页(如果你硬是想知道原理,mybatis拦截器,学习过后你就知道什么回事了)。

这篇博客先向大家展示怎么使用,过后有时间再讲他的实现原理。

1.添加maven依赖

1 <dependency>
2   <groupId>com.github.pagehelper</groupId>
3   <artifactId>pagehelper</artifactId>
4   <version>5.0.0</version>
5 </dependency>

2.在 Spring 配置文件中配置拦截器插件,也可以在mybatis的xml里面配置,但是两种配置不能同时出现,否则容易出现com.github.pagehelper.PageInterceptor插件出现空指针问题

在spring.xml中定义:

 1 <!--配置SqlSessionFactory对象 -->
 2     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
 3         <property name="dataSource" ref="dataSource" />
 4         <property name="configLocation" value="classpath:mybatis-config.xml" />
 5         <property name="typeAliasesPackage" value="com.aoChine.model.entity" />
 6         <property name="mapperLocations" value="classpath:mapper/*.xml" />
 7 
 8         <!-- 配置mybatis分页插件PageHelper -->
 9         <property name="plugins">
10             <array>
11                 <bean class="com.github.pagehelper.PageInterceptor">
12                     <property name="properties">
13                         <!-- 什么都不配,使用默认的配置 -->
14                         <value></value>
15                     </property>
16                 </bean>
17             </array>
18         </property>
19     </bean>

在mybatis-config.xml中定义

<plugins>
        <!-- com.github.pagehelper为PageHelper类所在包名 -->
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <!-- 使用MySQL方言的分页 -->
            <property name="helperDialect" value="sqlserver"/><!--如果使用mysql,这里value为mysql-->
            <property name="pageSizeZero" value="true"/>
        </plugin>
 </plugins>

3.使用

a)写正常查询语句的接口

mybatis pagehelper分页插件使用

接口:

mybatis pagehelper分页插件使用

b)在service层调用接口,实现分页。

mybatis pagehelper分页插件使用

分页插件使用这样就使用完毕了,博客只是介绍了最简单的使用方法,如果需要了解更多内容

这个是开源社区上面的插件库地址:
https://github.com/pagehelper/Mybatis-PageHelper/blob/master/README_zh.md
---------------------
作者:我爱奔跑的浮云
来源:CSDN
原文:https://blog.csdn.net/qq_26790807/article/details/62429290