Java 分页拦截类 , 供大家参考 , 具体内容如下
pacote com.opms.intercept; importar java.sql.connection; importar java.sql.preparedStatement; importar java.sql.resultset; importar java.sql.sqlexception; importar java.util.properties; importeter.andache.ibats.exector; org.apache.ibatis.executor.statement.statementHandler; importar org.apache.ibatis.logging.log; importar org.apache.ibatis.logging.logfactory; import org.apache.ibatis.mapping.boundsql; importação.apache.ibatis.apache.mapping.mapping.mapping.mapping.boundSql; importação.apache.ibatis.mapping.mapping.mapping.mapping.mapping.mapping.mapping; org.apache.ibatis.plugin.intercept; importe org.apache.ibatis.plugin.intercepts; importar org.apache.ibatis.plugin.invocation; importar org.apache.ibatis.plugin.plugin; import.apache.ibatis.PeLatin.signature; importination; importin; importimorn; importância; importimort.mport.mport.mport.mport.mport.mport.mport.mport.mport.mport.mport.mports ousknature; importobin; importância; import.apache.ibatis.Peath.Mignature; importação; importância; importância; org.apache.ibatis.reflection.factory.DefaultObjectFactory; importar org.apache.ibatis.reflection.factory.objectFactory; importação org.apache.ibatis.reflection.wapper.defappejectFormFetortory; import.apache.ibatis.reflection.wappers.obforen; org.apache.ibatis.scripting.defaults.defaultParameterHandler; importar org.apache.ibatis.session.rowbounds; importar com.wifi.core.page.page; ** ** * 通过拦截 <Code>Handler </code> 的 <code> preparar , 重写 重写 通过拦截 通过拦截 通过拦截*/@Intercepts ({@assinatura (type = declarationHandler.class, method = "preparar", args = {Connection.class})}) public class PageInterceptor implementa interceptor {/** *日志 */private static final logger = logFactory.getLog (PageIntercept.Class); / ** * 声明对象 */ private estático final ObjectFactory default_object_factory = new DefaultObjectFactory (); / ** * 声明对象 */ private estático final ObjectWrapperFactory default_object_wrapper_factory = new DefaultObjectWrapperFactory (); / ** * 数据库类型 (默认为 mysql) */ string estática privada defaultDialect = "mysql"; / ***需要拦截的 ID (正则匹配)*/ String estática privada DefaultPagesqlid = ".*4Page $"; / ** * 数据库类型 (默认为 mysql) */ string estática privada dialect = ""; / ** * 需要拦截的 ID (正则匹配) */ private Static String Pagesqlid = ""; / ** * @param Invocation 参数 * @return Objeto * @THOWSOWS THROTABLE 抛出异常 */ Public Object Intercept (Invocation Invocation) lança lançável {DeclarationHandler DeclarationHandler = (DeclarationHandler) Invocation.getTarget (); MetaObject metastatementHandler = metaobject.forObject (declaração -oral, default_object_factory, default_object_wrapper_factory); // 分离代理对象链 (由于目标类可能被多个拦截器拦截 , 从而形成多次代理 , 通过下面的两次循环可以分离出最原始的的目标类) while (metastatementHandler.hasgetter ("h")) {objeto objeto = metatatementHandler.getValue ("h"); metastatementHandler = metaobject.foroBject (objeto, default_object_factory, default_object_wrapper_factory); } // 分离最后一个代理对象的目标类 while (metastatementHandler.hasgetter ("Target")) {objeto objeto = metastatementHandler.getValue ("Target"); metastatementHandler = metaobject.foroBject (objeto, default_object_factory, default_object_wrapper_factory); } dialect = defaultDialect; PAGESQLID = defaultPagesqlid; /* Configuração da configuração = (Configuração) MetastatementHandler.getValue ("Delegate.configuration"); dialect = configuration.getvariables (). getProperty ("dialeto"); if (null == dialeto || "" .equals (dialeto)) {logger.warn ("O dialeto da propriedade não está definido, use padrão 'mysql'"); dialeto = defaultDialect; } PAGESQLID = Configuration.getvariables (). getProperty ("Pagesqlid"); if (null == PAGESQLID || "" .Equals (PAGESQLID)) {LOGGER.WARN ("Propriedade PAGESQLID não é definido, use padrão '.*Page $'"); PAGESQLID = defaultPagesqlid; }*/ Mapedstatement mapedstatement = (MappedStatement) metastatementHandler.getValue ("delegate.mappedstatement"); // 只重写需要分页的 sql 语句。通过 mapedstatement 的 id 匹配 , 默认重写以 página 结尾的 mapedstatement 的 sql if (mapedstatement.getId (). Corresponde (Pagesqlid)) {boundsql boundsql = (boundsql) metaTatendHandler.getValue ("delgate.Beound.Beound.Beound.Beound.Blate.Blate.Blate.Beoundsql = (Boundsql) Objeto parameterObject = boundSql.getParameToBject (); if (parameterObject == null) {lança nova nullPointerException ("parameterObject é nulo!"); } else {objeto obj = metatatementHandler .getValue ("delegate.boundsql.parameterObject.page"); // 传入了 página 参数且需要开启分页时 if (obj! = Null && obj instanceof Page && ((página) obj) .ispagination ()) {página página = (página) metastatementHandler .getValue ("delegate.boundsql.parameterOject.page"); String sql = boundsql.getSql (); // 重写 sql string pagesql = buildPagesql (sql, página); metastatementHandler.SetValue ("delegate.boundsql.sql", Pagesql); // 采用物理分页后 , 就不需要 mybatis 的内存分页了 , 所以重置下面的两个参数 MetastatementHandler.SetValue ("delegate.rowbounds.offset", rowbounds.no_row_offset); metastatementHandler.setValue ("delegate.rowbounds.limit", rowbounds.no_row_limit); Conexão de conexão = (conexão) invocação.getargs () [0]; // 重设分页参数里的总页数等 setPageParameter (SQL, conexão, MappedStatement, Boundsql, página); }}} // 将执行权交给下一个拦截器 retorna invocação.proeced (); }/** * 从数据库里查询总的记录数并计算总页数 , 回写进分页参数 <code> PageParameter </code>, 这样调用者就可用通过 分页参数 * <code> PageParameter </code> 获得相关信息。 * * @param sql 参数 * @param conexão 连接 * @param mapedstatement 参数 * @param limites MAPPEDSTATEMENT, BIETSQL BUMPLESQL, página da página) {// 记录总记录数 string countSql = "Selecione contagem (0) de (" + sql + ") como total"; Preparado countstmt countstmt = null; ResultSet rs = null; tente {countStmt = Connection.Preparestatement (countSQL); Boundsql countbs = new Boundsql (MappEdStatement.getConfiguration (), countSQL, boundsql.getParameTerMAppings (), Boundsql.getParameterObject ()); SetParameters (CountStmt, MappedStatement, Countbs, Boundsql.getParameterObject ()); rs = countstmt.executeQuery (); int totalCount = 0; if (rs.Next ()) {totalCount = rs.getInt (1); } página.SetTotalCount (TotalCount); Page.init (Page.getCurPage (), Page.getPagesize (), TotalCount); } catch (sqLexception e) {logger.error ("ignore esta exceção", e); } finalmente {tente {rs.close (); } catch (sqLexception e) {logger.error ("ignore esta exceção", e); } tente {countstmt.close (); } catch (sqLexception e) {logger.error ("ignore esta exceção", e); } } } /** * 对SQL参数(?)设值 * * @param ps 参数 * @param mappedStatement 参数 * @param boundSql 绑定sql * @param parameterObject 参数对象 * @throws SQLException 抛出sql异常 */ private void setParameters(PreparedStatement ps, MappedStatement mappedStatement, BoundSql Boundsql, objeto parameterObject) lança sqlexception {parameterHandHer ParameterHandler = new DefaultParameterHandler (MappEdStatement, ParameterObject, 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 (dialeto)) {Pagesql = buildPagesqlformysql (sql, página); } else if ("oracle" .equals (dialeto)) {Pagesql = BuildPagesqlFororacle (sql, página); } else {return sql; } retornar Pagesql.toString (); } else {return sql; }} / ** * mysql 的分页语句 * * @param sql 参数 * @param página 页 * @return string * / public StringBuilder BuildPagesqlformySQL (string sql, página) {stringbuilder Pagesql = new StringBuilder (100); String BeginRow = String.ValueOf ((Page.getCurPage () - 1) * Page.getPagesize ()); Pagesql.append (SQL); Pagesql.append ("limite" + BEGNROW + "," + Page.getPagesize ()); retornar PAGESQL; } / ** * 参考 Hibernate 的实现完成 Oracle 的分页 * * @param sql 参数 * @param página 参数 * @return string * / public StringBuilder BuildPagesqlFororacle (String sql, página da 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 ("Selecione * de (selecione Temp. retornar PAGESQL; } / ** * @param alvo 参数 * @return objeto * / public Object Plugin (destino do objeto) {// 当目标类是 DeclarationHandler 类型时 , 才包装目标类 , 否者直接返回目标本身, 减少目标被代理的次数 if (Instância do destinofHandHandler) {return plugin.wrap (Target, this); } else {return Target; }} / ** * @param Properties 参数 * / public void setProperties (Propriedades Propriedades) {}}以上就是本文的全部内容 , 希望对大家的学习有所帮助 , 也希望大家多多支持武林网。