本文实例为大家分享了完整的 java 分页拦截类 , 供大家参考 具体内容如下
paquete com.opms.interceptor; import java.sql.connection; import java.sql.preparedStatement; import java.sql.ResultSet; import java.sql.sqlexception; import java.util.properties; import opache.ibatis.executor.parameter org.apache.ibatis.executor.statement.statementHandler; import org.apache.ibatis.logging.log; importar org.apache.ibatis.logging.logfactory; importar org.apache.ibatis.mapping.boundsql; import org.apache.ibatis.mappingspppingsppedSpapts; importar; importación; importación; importación; importación; importación; importación; org.apache.ibatis.plugin.interceptor; import org.apache.ibatis.plugin.intercepts; import org.apache.ibatis.plugin.invocation; importar org.apache.plugin.plugin; import.apache.ibatis.plugin.signature; org.apache.ibatis.Reflection.Factory.defaultObjectFactory; import org.apache.ibatis.reflection.Factory.ObjectFactory; import org.apache.ibatis.reflection.wrappers.defefaultWrapperfactory; import org.apache.ibatis.scripting.default.defaultparameterhandler; import org.apache.ibatis.session.rowbounds; import com.wifi.core.page.page;/** * 通过拦截 <code> DeclarationHandler </código> 的 <código> preparar </código> 方法 重写 重写 重写 老规矩 签名里要拦截的类型只能是接口。 签名里要拦截的类型只能是接口。 签名里要拦截的类型只能是接口。 , , , , * */@Intercepts ({@firma (type = DeclaryHandler.class, método = "Preparar", args = {Connection.Class})}) Class pública PageInterceptor Implementa el interceptor {/** *日志 */privado estático Logger final = logFactory.getLog (PageInterceptor.class); / ** * 声明对象 */ Private static final ObjectFactory Default_Object_Factory = new DefaultObjectFactory (); / ** * 声明对象 */ Private Static 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 páginasqlid = ""; / ** * @param Invocation 参数 * @return objeto * @throws showable 抛出异常 */ public object Intercept (Invocation Invocation) lanza Showleable {DeclaryHandler DeclarationHandler = (DeclarationHandler) Invocation.getTarget (); MetaObject MetaStatementHandler = metaObject.forObject (DeclarationHandler, default_object_factory, default_object_wrapper_factory); // 分离代理对象链 (由于目标类可能被多个拦截器拦截 , 从而形成多次代理 , 通过下面的两次循环可以分离出最原始的的目标类) while (metastatementHandler.hasgetter ("h")) {objeto objeto = metastatementHandler.getValue ("h"); metastatementHandler = metaObject.forObject (objeto, default_object_factory, default_object_wrapper_factory); } // 分离最后一个代理对象的目标类 while (metastatementHandler.hasgetter ("target")) {object object = metastatementHandler.getValue ("target"); metastatementHandler = metaObject.forObject (objeto, default_object_factory, default_object_wrapper_factory); } dialecto = defaultDialect; pagesqlid = defaultpagesqlid; /* Configuración Configuración = (Configuración) MetastatementHandler.getValue ("Delegate.Configuration"); dialect = configuration.getVariables (). GetProperty ("dialecto"); if (null == dialecto || "" .equals (dialecto)) {logger.warn ("El dialecto de la propiedad no está configurado, use el valor predeterminado 'mysql'"); dialecto = defaultdialect; } pagesqlid = Configuration.getVariables (). GetProperty ("Pagesqlid"); if (null == Pagesqlid || "" .equals (pagesqlid)) {logger.warn ("PROPIEDAD PAGESQLID NO ESTÁ LA pageSqlid = DefaultPagesqLid; }*/ MappedStatement MappedStatement = (MappedStatement) MetastatementHandler.getValue ("Delegate.MappedStatement"); // 只重写需要分页的 SQL 语句。通过 MappedStatement 的 ID 匹配 , 默认重写以 Página 结尾的 MappedStatement 的 sql if (mappedStatement.getId (). Matches (Pagesqlid)) {BoundSQL BoundSql = (BoundSQL) MetastatementHandler.getValue ("delegate.Boundsql"); Objeto parametREAnt = boundSql.getParametRoCject (); if (parametREAncject == null) {tire nueva nullPointerException ("ParametRETObject es nulo!"); } else {object obj = metastatementHandler .getValue ("delegate.boundsql.parameteroBject.page"); // 传入了 Página 参数且需要开启分页时 if (obj! = NULL && obj instanceOf Page && ((Page) obj) .IsPAgination ()) {Page Page = (Page) MetastatementHandler .getValue ("delegate.boundsql.ParameteroBject.Page"); Cadena sql = boundsql.getSql (); // 重写 SQL String Pagesql = BuildPagesql (SQL, Page); metastatementHandler.setValue ("delegate.boundsql.sql", páginasql); // 采用物理分页后 , 就不需要 MyBatis 的内存分页了 , 所以重置下面的两个参数 MetastatementHandler.SetValue ("delegate.rowbounds.offset", rowbounds.no_row_offset); metastatementHandler.setValue ("delegate.rowbounds.limit", rowbounds.no_row_limit); Conexión Connection = (Connection) Invocat.GetArgs () [0]; // 重设分页参数里的总页数等 setPageParameter (SQL, Connection, MappedStatement, BoundSQL, página); }}} // 将执行权交给下一个拦截器 return invocation.proced (); }/** * 从数据库里查询总的记录数并计算总页数 , 回写进分页参数 <code> PageParameter </code>, 这样调用者就可用通过 分页参数 * <code> pagParameter </code> 获得相关信息。 * * @param sql 参数 * @param Connection 连接 * @param mappedStatement 参数 * @param Boundsql 绑定 sql * @param página 页 */private void setpageParameter (string sql, conexe, conexión, conexión, conexión, mapePEdStattattattat, mapePedStat, MAPPEdSTAT, MAPPEdStat, MapePedStat, MAPPEdStat. MappedStatement, BoundSQL BoundSql, página de página) {// 记录总记录数 String CountSql = "Seleccione Count (0) desde (" + SQL + ") como Total"; Preparado en cuenta CountStmt = null; ResultSet rs = null; intente {countStmt = Connection.PrepareStatement (CountSql); Boundsql CountBs = new BoundSQL (MappedStatement.getConfiguration (), CountSql, BoundSql.getParametermappings (), BoundSql.getParametRangject ()); setParameters (CountStmt, MappedStatement, Countbs, Boundsql.getParametreEpject ()); 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 ("ignorar esta excepción", e); } finalmente {try {rs.close (); } catch (sqlexception e) {logger.error ("ignorar esta excepción", e); } try {countstmt.close (); } catch (sqlexception e) {logger.error ("ignorar esta excepción", e); }}}} / ** * 对 sql 参数 (?) 设值 * * @param ps 参数 * @param mappedStatement 参数 * @param boundsql 绑定 sql * @param parameteterOnt 参数对象 * @throws sqlexception 抛出 sql 异常 * / private void setParameters (preparado BoundSql, Object ParameterObject) lanza SQLException {ParameterHandler ParameterHandler = new DefaultParameterHandler (MappedStatement, ParametREAncject, BoundSql); ParameterHandler.SetParameters (PS); } / ** * 根据数据库类型 , 生成特定的分页 生成特定的分页 sql * * @param sql 餐宿 * @param página 页 * @return string * / private string buildPagesql (string sql, página página) {if (página! = Null) {StringBuilder Pagesql = new StringBuilder (); if ("mysql" .equals (dialect)) {pagesql = buildPagesqlFormysql (sql, página); } else if ("oracle" .equals (dialect)) {pagesql = buildPagesqlFororacle (sql, página); } else {return sql; } return pagesql.ToString (); } else {return sql; }} / ** * mysql 的分页语句 * * @param sql 参数 * @param página 页 * @return string * / public stringBuilder buildPagesqlFormySql (string sql, página página) {stringBuilder PageSQL = new StringBuilder (100); String beginRow = String.ValueOf ((Page.getCurPage () - 1) * Page.getPageSize ()); páginasql.append (SQL); PAGEQL.Append ("Limit" + BeginRow + "," + Page.getPagesize ()); retorno páginasql; } / ** * 参考 Hibernate 的实现完成 Oracle 的分页 * * @param sql 参数 * @param página 参数 * @return string * / public stringBuilder buildPagesqlFororacle (string sql, página de página) {StringBuilder Pagesql = new StringBuilder (100); String beginRow = String.ValueOf ((Page.getCurPage () - 1) * Page.getPageSize ()); String endrow = string.ValueOf (page.getCurPage () * page.getPageSize ()); pagesql.append ("Seleccionar * de (Seleccione temp. *, Rownum Row_id desde ("); Pagesql.Append (SQL); Pagesql.Append (") TEMP WHERE ROWNUM <=") .Append (EndRow); Pagesql.Append (") Where Row_id>") .Append (Beginrow); retorno páginasql; } / ** * @param Target 参数 * @return objeto * / plugin de objeto público (objetivo de objeto) {// 当目标类是 DeclarationHandler 类型时 才包装目标类 , 否者直接返回目标本身 否者直接返回目标本身 减少目标被代理的次数 减少目标被代理的次数 减少目标被代理的次数 if (Target instanceOf DeclarationHandler) {return plugin.wrap (target, this); } else {Target de retorno; }} / ** * @param propiedades 参数 * / public void setProperties (propiedades de propiedades) {}}以上就是本文的全部内容 , 希望对大家的学习有所帮助 也希望大家多多支持武林网。 也希望大家多多支持武林网。