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)寫正常查詢語句的接口

接口:

b)在service層調用接口,實現分頁。

分頁插件使用這樣就使用完畢了,博客只是介紹了最簡單的使用方法,如果需要了解更多內容

這個是開源社區上面的插件庫地址:
https://github.com/pagehelper/Mybatis-PageHelper/blob/master/README_zh.md
---------------------
作者:我愛奔跑的浮雲
來源:CSDN
原文:https://blog.csdn.net/qq_26790807/article/details/62429290


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM