1. 程式人生 > >Mybatis的分頁外掛PageHelper

Mybatis的分頁外掛PageHelper

 

外掛官方文件地址:https://github.com/pagehelper/Mybatis-PageHelper/blob/master/README_zh.md

使用方法:https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.md

PageHelper是一款好用的開源免費的Mybatis第三方物理分頁外掛

 

1、pom.xml 引入  pagehelper 依賴

<!-- pagehelper -->
		<dependency>
		    <groupId>com.github.pagehelper</groupId>
		    <artifactId>pagehelper</artifactId>
		    <version>5.1.4</version>
		</dependency>

2、在Mybatis中全域性配置檔案中配置攔截器

<!-- 在environments標籤的前面 -->
	<plugins>
		<plugin interceptor="com.github.pagehelper.PageInterceptor">
			<!-- 設定資料庫型別 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六種資料庫-->
            <property name="helperDialect" value="mysql"/>
		</plugin>
	</plugins>

3、sql對映檔案

  public List<User> selectUserBylike(@Param("username") String username,
				     @Param("state") Integer state);

  <select id="selectUserBylike" resultType="cn.jq.mybatis.model.User">		
	  select 
	  	<include refid="Base_Column_List" /> 
	  from t_user
	  <where>
		  <if test="username != null and username != ''">			
		  		and username like concat('%',concat(#{username},'%')) 	
		  </if>		
		  <if test="state != null and state >= 0">			
		  		and state like #{state}		
		  </if>	
	  </where>		
  </select>

4、分頁外掛支援好幾種呼叫方式:Mapper介面方式的呼叫,推薦這種使用方式

   只有緊跟在PageHelper.startPage方法後的第一個Mybatis的查詢(Select)方法會被分頁。

   返回 PagerInfo 型別,它裡邊包含了更豐富的分頁資訊

			Page<User> Page = PageHelper.startPage(1, 10);//第1頁的10個數據
			
			//List<User> userList = userMapper.selectUserBylike("admin",1);
			List<User> userList = userMapper.selectUserBylike(null,null);
			
			//使用PageInfo物件獲取,目的是把List強轉成Page物件,從而得到分頁結果  
			PageInfo<User> pageInfo = new PageInfo<>(userList);
			System.out.println(pageInfo);
			System.out.println(pageInfo.getTotal());
			System.out.println(pageInfo.isHasNextPage());

 

 

注意:什麼時候會導致不安全的分頁?

PageHelper 方法使用了靜態的 ThreadLocal 引數,分頁引數和執行緒是繫結的。

只要你可以保證在 PageHelper 方法呼叫後緊跟 MyBatis 查詢方法,這就是安全的。因為 PageHelper 在 finally 程式碼段中自動清除了 ThreadLocal 儲存的物件。

如果程式碼在進入 Executor 前發生異常,就會導致執行緒不可用,這屬於人為的 Bug(例如介面方法和 XML 中的不匹配,導致找不到 MappedStatement 時), 這種情況由於執行緒不可用,也不會導致 ThreadLocal 引數被錯誤的使用。

 

參考文章:PageHelper分頁外掛原始碼及原理剖析