一個好的講解mybatis的博客地址http://www.jianshu.com/nb/5226994
引言
對於使用Mybatis時,最頭痛的就是寫分頁,需要先寫一個查詢count的select語句,然后再寫一個真正分頁查詢的語句,當查詢條件多了之后,會發現真不想花雙倍的時間寫count和select,
如下就是項目在沒有使用分頁插件的時候的語句
<!-- 根據查詢條件獲取查詢獲得的數據量 --> <select id="size" parameterType="Map" resultType="Long"> select count(*) from help_assist_student <where> <if test="stuId != null and stuId != ''"> AND stu_id like CONCAT(CONCAT('%', #{stuId,jdbcType=VARCHAR}),'%') </if> <if test="name != null and name != ''"> AND name like CONCAT(CONCAT('%', #{name,jdbcType=VARCHAR}),'%') </if> <if test="deptId != null"> AND dept_id in <foreach item="item" index="index" collection="deptId" open="(" separator="," close=")"> #{item} </foreach> </if> <if test="bankName != null"> AND bank_name in <foreach item="item" index="index" collection="bankName" open="(" separator="," close=")"> #{item} </foreach> </if> </where> </select> <!-- 分頁查詢獲取獲取信息 --> <select id="selectByPageAndSelections" parameterType="cn.edu.uestc.smgt.common.QueryBase" resultMap="BaseResultMap"> select * from help_assist_student <where> <if test="parameters.stuId != null and parameters.stuId != ''"> AND stu_id like CONCAT(CONCAT('%', #{parameters.stuId,jdbcType=VARCHAR}),'%') </if> <if test="parameters.name != null and parameters.name != ''"> AND name like CONCAT(CONCAT('%', #{parameters.name,jdbcType=VARCHAR}),'%') </if> <if test="parameters.deptId != null"> AND dept_id in <foreach item="item" index="index" collection="parameters.deptId" open="(" separator="," close=")"> #{item} </foreach> </if> <if test="parameters.bankName != null"> AND bank_name in <foreach item="item" index="index" collection="parameters.bankName" open="(" separator="," close=")"> #{item} </foreach> </if> </where> order by dept_id,stu_id limit #{firstRow},#{pageSize} </select>
可以發現,重復的代碼太多,雖然說復制粘貼簡單的很,但是文件的長度在成倍的增加,以后翻閱代碼的時候頭都能大了。
於是希望只寫一個select語句,count由插件根據select語句自動完成。找啊找啊,發現PageHelperhttps://github.com/pagehelper/Mybatis-PageHelper 符合要求,於是就簡單的寫了一個測試項目
1,配置分頁插件:
直接從官網上copy的如下:
Config PageHelper 1. Using in mybatis-config.xml <!-- In the configuration file, plugins location must meet the requirements as the following order: properties?, settings?, typeAliases?, typeHandlers?, objectFactory?,objectWrapperFactory?, plugins?, environments?, databaseIdProvider?, mappers? --> <plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <!-- config params as the following --> <property name="param1" value="value1"/> </plugin> </plugins> 2. Using in Spring application.xml config org.mybatis.spring.SqlSessionFactoryBean as following: <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- other configuration --> <property name="plugins"> <array> <bean class="com.github.pagehelper.PageInterceptor"> <property name="properties"> <!-- config params as the following --> <value> param1=value1 </value> </property> </bean> </array> </property> </bean>
我使用第一中方法:
<!-- 配置分頁插件 --> <plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <!-- 設置數據庫類型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六種數據庫--> <property name="helperDialect" value="mysql"/> </plugin> </plugins>
其余的關於mybatis整合spring的內容就不用提了。
2,編寫mapper.xml文件
測試工程就不復雜了,簡單的查詢一個表,沒有條件
<select id="selectByPageAndSelections" resultMap="BaseResultMap"> SELECT * FROM doc ORDER BY doc_abstract </select>
然后在Mapper.java中編寫對應的接口
public List<Doc> selectByPageAndSelections();
3,分頁
@Service public class DocServiceImpl implements IDocService { @Autowired private DocMapper docMapper; @Override public PageInfo<Doc> selectDocByPage1(int currentPage, int pageSize) { PageHelper.startPage(currentPage, pageSize); List<Doc> docs = docMapper.selectByPageAndSelections(); PageInfo<Doc> pageInfo = new PageInfo<>(docs); return pageInfo; } }
參考文檔說明,我使用了PageHelper.startPage(currentPage, pageSize);
我認為這種方式不入侵mapper代碼。
其實一開始看到這段代碼時候,我覺得應該是內存分頁。其實插件對mybatis執行流程進行了增強,添加了limit以及count查詢,屬於物理分頁
再粘貼一下文檔說明中的一段話
4. 什么時候會導致不安全的分頁? PageHelper 方法使用了靜態的 ThreadLocal 參數,分頁參數和線程是綁定的。 只要你可以保證在 PageHelper 方法調用后緊跟 MyBatis 查詢方法,這就是安全的。因為 PageHelper 在 finally 代碼段中自動清除了 ThreadLocal 存儲的對象。 如果代碼在進入 Executor 前發生異常,就會導致線程不可用,這屬於人為的 Bug(例如接口方法和 XML 中的不匹配,導致找不到 MappedStatement 時), 這種情況由於線程不可用,也不會導致 ThreadLocal 參數被錯誤的使用。 但是如果你寫出下面這樣的代碼,就是不安全的用法: PageHelper.startPage(1, 10); List<Country> list; if(param1 != null){ list = countryMapper.selectIf(param1); } else { list = new ArrayList<Country>(); } 這種情況下由於 param1 存在 null 的情況,就會導致 PageHelper 生產了一個分頁參數,但是沒有被消費,這個參數就會一直保留在這個線程上。當這個線程再次被使用時,就可能導致不該分頁的方法去消費這個分頁參數,這就產生了莫名其妙的分頁。 上面這個代碼,應該寫成下面這個樣子: List<Country> list; if(param1 != null){ PageHelper.startPage(1, 10); list = countryMapper.selectIf(param1); } else { list = new ArrayList<Country>(); } 這種寫法就能保證安全。 如果你對此不放心,你可以手動清理 ThreadLocal 存儲的分頁參數,可以像下面這樣使用: List<Country> list; if(param1 != null){ PageHelper.startPage(1, 10); try{ list = countryMapper.selectAll(); } finally { PageHelper.clearPage(); } } else { list = new ArrayList<Country>(); } 這么寫很不好看,而且沒有必要。
4,結果
controller層中簡單的調用然后返回json字符串如下:可以看出,結果基於doc_abstract排序后返回1-10條的數據
結語
盡量不要重復造輪子。