本文实例为大家分享了完整的 Java 分页拦截类 , 供大家参考 , 具体内容如下
package com.opms.interceptor; import java.sql.connection; import java.sql.preparedstatement; import java.sql.resultSet; import java.sql.sqlexception; import java.util.properties; import org.apache.ibatis.executor.prometer.prometerhandler; org.apache.ibatis.executor.station.statementhandler; import org.apache.ibatis.logging.log; import org.apache.ibatis.logging.logfactory; import org.apache.mapping.mapping.boundsql; import org.apache.ibatis.mapping.maptstatique; importation; import org.apache.ibatis.plugin.interceptor; import org.apache.ibatis.plugin.intercepts; import org.apache.ibatis.plugin.invocation; import org.apache.ibatis.plugin.plugin; import org.apache.ibatis.plugin.signature; import org.apache.ibatis.reflection. org.apache.ibatis.reflection.factory.defaultObjectFactory; import org.apache.ibatis.reflection.factory.objectfactory; import org.apache.ibatis.reflection.wrapper.DefaultBjectWrapperFactory; import org.apache.ibatis.reflection.wraper.ObjectFactory; import org.apache.ibatis.scripting.defaults.defaultParameterHandler; Import org.apache.ibatis.session.rowbounds; importer com.wifi.core.page.page; / ** * 通过拦截 <code> instructionshandler </ code> 的 </ code> 方法 , 重写 重写 sql 语句实现物理分页。 * 老规矩 , 签名里要拦截的类型只能是接口。 * * * * / @ Intercepts ({@ signature (type = instructionHandler.class, méthode = "prépare", args = {connection.class})}) public class PageInterceptor implémente interceptor {/ ** * 日志 * / private static Logger Logger = logFactory.getLog (pageInterceptor.Class); / ** * 声明对象 * / private static final objectFactory default_object_factory = new defaultObjectFactory (); / ** * 声明对象 * / private statique final objectwrapperfactory default_object_wrapper_factory = new defaultObjectWrapperFactory (); / ** * 数据库类型 (默认为 mysql) * / private static String defaultDialect = "mysql"; / ** * 需要拦截的 id (正则匹配) * / private static String defaultPagesqlid = ". * 4Page $"; / ** * 数据库类型 (默认为 mysql) * / private static String dialect = ""; / ** * 需要拦截的 id (正则匹配) * / private static String pagesqlid = ""; / ** * @param invocation 参数 * @return objet * @Throws Throwable 抛出异常 * / public Object Intercept (invocation invocation) lève le throwable {instructionHandler StatementHandler = (statutHandler) invocation.getTarget (); MetaObject MetastatementHandler = metaObject.ForObject (instructionHandler, default_object_factory, default_object_wrapper_factory); // 分离代理对象链 (由于目标类可能被多个拦截器拦截 , 从而形成多次代理 , 通过下面的两次循环可以分离出最原始的的目标类) while (metaStationHandler.hasgetter ("h")) {objet objet = metaStationHandler.getValue ("h"); MetaStationHandler = metaObject.ForObject (objet, default_object_factory, default_object_wrapper_factory); } // 分离最后一个代理对象的目标类 while (metastatementhandler.hasgetter ("cible")) {objet objet = metaStationHandler.getValue ("Target"); MetaStationHandler = metaObject.ForObject (objet, default_object_factory, default_object_wrapper_factory); } dialect = defaultdialect; pagesqlid = defaultPagesQLid; / * Configuration Configuration = (Configuration) MetastatementHandler.getValue ("Delegate.configuration"); dialect = configuration.getVariables (). getProperty ("dialect"); if (null == dialect || "" .equals (dialect)) {logger.warn ("Le dialect de propriété n'est pas configuré, utilisez default 'mysql'"); dialect = defaultDialect; } pagesqlid = configuration.getVariables (). getProperty ("pagesqlid"); if (null == pagesqlid || "" .equals (pagesqlid)) {logger.warn ("La propriété pagesqlid n'est pas définie, utilise default '. * page $'"); pagesqlid = defaultPagesQLid; } * / MAPPEDSATATION MAPPEDSATAMENT = (MAPPEDSATATION) MetastatementHandler.GetValue ("Delegate.Maptstatement"); // 只重写需要分页的 SQL 语句。通过 MAPPEDSTATATION 的 ID 匹配 , 默认重写以 PAGE 结尾的 MAPTEDSTATATION 的 SQL IF (MAPPEDSTAMENT.GETID (). Matches (PagesQLid)) {BOUNDSQL BOUNDSQL = (BOUNDSQL) MetastatementHandler.getValue ("Delegate.BoundsSQL"); Object ParameterObject = boundsql.getParameterObject (); if (ParameterObject == NULL) {Throw New NullPointerException ("ParameterObject est null!"); } else {objet obj = metastatementHandler .getValue ("Delegate.boundsql.ParameterObject.Page"); // 传入了 Page 参数且需要开启分页时 if (obj! = Null && instance OBJ page && ((page) obj) .ispagination ()) {page page = (page) metastationhandler .getValue ("delegate.boundsql.ParameterObject.page"); String sql = boundsql.getsql (); // 重写 SQL String pagesql = buildPagesql (sql, page); MetaStationHandler.SetValue ("Delegate.boundsql.sql", pagesql); // 采用物理分页后 , 就不需要 MyBatis 的内存分页了 , 所以重置下面的两个参数 MetastatementHandler.setValue ("Delegate.Rowbounds.offset", rowbounds.no_row_offset); MetaStationHandler.SetValue ("Delegate.Rowbounds.limit", Rowbounds.no_row_limit); Connexion connexion = (connexion) invocation.getArgs () [0]; // 重设分页参数里的总页数等 SetPageParameter (SQL, Connection, MaptedStatement, BoundsQL, page); }}} // 将执行权交给下一个拦截器 return invocation.proceed (); } / ** * 从数据库里查询总的记录数并计算总页数 , 回写进分页参数 <Code> PageParameter </code>, 这样调用者就可用通过 分页参数 * <code> PageParameter </code> 获得相关信息。 * * @param sql 参数 * @param connexion 连接 * @param mappedstatement 参数 * @param boundsql 绑定 sql * @param page 页 * / privil MapPedStatement, BoundsQL BoundsQL, page page) {// 记录总记录数 String CountSql = "Select Count (0) From (" + SQL + ") As Total"; PRÉPAYÉSATATION COUNTSTMT = NULL; ResultSet rs = null; try {countstmt = connection.preparestatement (countSQL); BOUNDSQL COUNTBS = NOUVEAU BOURNSQL (MAPPEDSATATION.GETCONFIGURATION (), COUNTSQL, BOUNDSQL.GetParameTermAppings (), BOUNDSQL.GetParameterObject ()); setParameters (countstmt, maptedstatement, countbs, boundsql.getParameterObject ()); rs = countstmt.executequery (); int totalCount = 0; if (Rs.Next ()) {totalCount = Rs.GetInt (1); } page.setTotalCount (totalCount); page.init (page.getCurpage (), page.getPageSize (), totalCount); } catch (sqlexception e) {logger.error ("ignorer cette exception", e); } enfin {try {Rs.close (); } catch (sqlexception e) {logger.error ("ignorer cette exception", e); } essayez {countstmt.close (); } catch (sqlexception e) {logger.error ("ignorer cette exception", e); }}} / ** * 对 sql 参数 (?) 设值 * * @param ps 参数 * @param mappedstatement 参数 * @param bounddsql 绑定 sql * @param ParameterObject 参数对象 * @throws sqlexception 抛出 sql 异常 * / private SetParameters (préparé PS, MAPPEDSTATETISE MAPPED MAPPED MAPPEDSTATEMENT, PREPEPTSAMENT PS, MAPPEDSTATETISEM BoundsQL, Object ParameterObject) lève SQException {ParameterHandler ParameterHandler = new defaultParameterHandler (maptedstatement, ParameterObject, BoundsQL); ParameterHandler.SetParameters (PS); } / ** * 根据数据库类型 , 生成特定的分页 sql * * @param sql 餐宿 * @param page 页 * @return String * / private String buildPagesql (String sql, page page) {if (page! = Null) {StringBuilder pagesql = new StringBuilder (); if ("mysql" .equals (dialect)) {pagesql = buildPagesQlformySQL (sql, page); } else if ("oracle" .equals (dialect)) {pagesql = buildPagesqlFororacle (sql, page); } else {return sql; } return pagesql.toString (); } else {return sql; }} / ** * mysql 的分页语句 * * @param sql 参数 * @param page 页 * @return String * / public StringBuilder buildPagesQlformySQL (String sql, page page) {stringBuilder pagesql = new StringBuilder (100); String beginrow = string.valueof ((page.getCurpage () - 1) * page.getPageSize ()); pagesql.append (SQL); pagesql.append ("limite" + beginrow + "," + page.getPageSize ()); return pagesql; } / ** * 参考 Hibernate 的实现完成 Oracle 的分页 * * @param sql 参数 * @param page 参数 * @return String * / public StringBuilder buildPagesqlfororacle (String sql, page page) {StringBuilder pagesql = new StringBuilder (100); String beginrow = string.valueof ((page.getCurpage () - 1) * page.getPageSize ()); String Endrow = String.ValueOf (page.getCurpage () * page.getPageSize ()); pagesql.append ("SELECT * From (select temp. *, rownum row_id from ("); pagesql.append (sql); pagesql.append (") temp où rownum <=") .append (endrow); pagesql.append (") where row_id>") .Apnd (débutant); return pagesql; } / ** * @param Target 参数 * @return Object * / Public Object Plugin (Object Target) {// 当目标类是 StatementHandler 类型时 , 才包装目标类 , 否者直接返回目标本身, 减少目标被代理的次数 if (cible instanceof statuehandler) {return plugin.wrap (cible, this); } else {return Target; }} / ** * @param Propriétés 参数 * / public void setProperties (Propriétés Propriétés) {}}以上就是本文的全部内容 , 希望对大家的学习有所帮助 , 也希望大家多多支持武林网。