1. SQL 分頁(yè)
<select id="queryStudentsBySql" parameterType="map" resultMap="studentmapper">?
? ? ? ? ? ?select * from student limit #{currIndex} , #{pageSize}
</select>
創(chuàng)建攔截器,攔截mybatis接口方法id以ByPage結(jié)束的語(yǔ)句
? ? ? ? ?String sql = (String) MetaObjectHandler.getValue("delegate.boundSql.sql");
? ? ? ? ? ? //也可以通過(guò)statementHandler直接獲取
? ? ? ? ? ? //sql = statementHandler.getBoundSql().getSql();
? ? ? ? ? ? //構(gòu)建分頁(yè)功能的sql語(yǔ)句? ? ? ? ? ? String limitSql;
? ? ? ? ? ? sql = sql.trim();
? ? ? ? ? ? limitSql = sql + " limit " + (currPage - 1) * pageSize + "," + pageSize;
? ? ? ? ? ? //將構(gòu)建完成的分頁(yè)sql語(yǔ)句賦值個(gè)體'delegate.boundSql.sql',偷天換日? ? ? ? ? ?MetaObjectHandler.setValue("delegate.boundSql.sql", limitSql);
<configuration>
? ? <plugins>
? ? ? ? ? ? ? ? ? ?<plugin interceptor="com.autumn.interceptor.MyPageInterceptor">
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?<property name="limit" value="10"/>
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?<property name="dbType" value="mysql"/>
? ? ? ? ? ? ? ? ? </plugin>
? ? ? ? ? </plugins>
</configuration>
通過(guò)自定義插件的形式實(shí)現(xiàn)分頁(yè),也是最好的,也叫做分頁(yè)攔截器。實(shí)現(xiàn)步驟如下:
插件支持MySQL和Oracle兩種數(shù)據(jù)庫(kù),通過(guò)方法名關(guān)鍵字ListPage去匹配,有才進(jìn)行分頁(yè)處理,并且不用在Mapping中寫分頁(yè)代碼。
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
? ? <typeAliases>
? ? ? ? <typeAlias alias="PageInfo" type="com.jsoft.testmybatis.util.PageInfo" />
? ? </typeAliases>
? ? <plugins>
? ? ? ? <plugin interceptor="com.jsoft.testmybatis.util.PagePlugin">
? ? ? ? ? ? <property name="dialect" value="mysql" />
? ? ? ? ? ? <property name="pageSqlId" value=".*ListPage.*" />
? ? ? ? </plugin>
? ? </plugins>
</configuration>
3. RowBounds分頁(yè)
Mybatis使用RowBounds對(duì)象進(jìn)行分頁(yè),它是針對(duì)ResultSet結(jié)果集執(zhí)行的內(nèi)存分頁(yè),而非物理分頁(yè),可以在sql內(nèi)直接書寫帶有物理分頁(yè)的參數(shù)來(lái)完成物理分頁(yè)功能,也可以使用分頁(yè)插件來(lái)完成物理分頁(yè)。
數(shù)據(jù)量小時(shí),RowBounds不失為一種好辦法。但是數(shù)據(jù)量大時(shí),實(shí)現(xiàn)攔截器就很有必要了。
mybatis接口加入RowBounds參數(shù)
(1)Dao:
public List?queryUsersByPage(String userName, RowBounds rowBounds);
(2)Service:
? @Override
? ? @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.SUPPORTS)
? ? publicList queryRolesByPage(String roleName,intstart,int limit) {
? ? ? ? returnroleDao.queryRolesByPage(roleName,new RowBounds(start, limit));
? ? }
分頁(yè)插件的基本原理是使用Mybatis提供的插件接口,實(shí)現(xiàn)自定義插件,在插件的攔截方法內(nèi)攔截待執(zhí)行的sql,然后重寫sql,根據(jù)dialect方言,添加對(duì)應(yīng)的物理分頁(yè)語(yǔ)句和物理分頁(yè)參數(shù)。
舉例:select * from student,攔截sql后重寫為:select t.* from (select * from student)t?limit 0,10
作者:代碼之尖
鏈接:http://www.itdecent.cn/p/eed3f2e24b83
來(lái)源:簡(jiǎn)書
簡(jiǎn)書著作權(quán)歸作者所有,任何形式的轉(zhuǎn)載都請(qǐng)聯(lián)系作者獲得授權(quán)并注明出處。