1. 封装分页 Página 类
pacote com.framework.common.page.impl; importar java.io.serializable; importar com.framework.common.page.ipage;/** ** * * */public class. */ private estático final serialversionuid = -3623448612757790359l; public static int default_page_size = 20; private int pageSize = default_page_size; private int currentResult; private int totalpage; private int currentpage = 1; private int totalCount = -1; public BasePage (int currentPage, int PageSize, int totalCount) {this.currentPage = currentPage; this.Pagesize = PageSize; this.TotalCount = TotalCount; } public int getTotalCount () {return this.totalCount; } public void SettaltalCount (int totalCount) {if (totalCount <0) {this.totalCount = 0; retornar; } this.TotalCount = totalCount; } public BasEpage () {} public int getFirstresult () {return (this.currentPage - 1) * this.pagesize; } public void setPagesize (int paGageSize) {if (PageSize <0) {this.pagesize = default_page_size; retornar; } this.Pagesize = Pagesize; } public int getTotalPage () {if (this.totalpage <= 0) {this.totalpage = (this.totalCount / this.pagesize); if ((this.totalPage == 0) || (this.totalCount % this.pagesize! = 0)) {this.totalpage += 1; }} Retorne this.TotalPage; } public int getPagesize () {return this.pagesize; } public void setPageno (int currentPage) {this.currentpage = currentpage; } public int getpageno () {return this.currentPage; } public boolean isfirstpage () {return this.currentpage <= 1; } public boolean ISLASTPAGE () {return this.currentpage> = getTotalPage (); } public int getNextPage () {if (islastPage ()) {return this.currentPage; } return this.currentPage + 1; } public int getCurrentResult () {this.currentResult = ((getPageno () - 1) * getPagesize ()); if (this.currentResult <0) {this.currentResult = 0; } retorne este.CurrentResult; } public int getPrepage () {if (isfirstpage ()) {return this.currentPage; } retornar this.CurrentPage - 1; }}
pacote com.framework.common.page.impl; importar java.util.list;/** * * * */página pública Página estende a base de base {/** * */serialversion final estático privado = -97017792870937315L; public static threadlocal <age> threadlocal = new Threadlocal <age> (); Dados da lista privada <?>; public Page () {} PÁGINA PUBLICA (INT CurrentPage, int PageSize, int TotalCount) {Super (CurrentPage, PageSize, TotalCount); } página pública (int currentPage, int PageSize, int TotalCount, List <?> Data) {super (CurrentPage, PageSize, TotalCount); this.data = dados; } list public <?> getData () {retornar dados; } public void setData (list <?> data) {this.data = data; }}
2. 封装分页插件
pacote com.framework.common.page.plugin; importar java.sql.connection; importar java.sql.preparedStatement; importar java.sql.resultset; importar java.sql.sqLexception; .Properties; importar javax.xml.bind.propertyException; importar org.apache.commons.lang3.stringutils; importar org.apache.ibatis.executor.errorContext; importar org.apache.ibatis.executor.executorException; importação; ibatis.executor.statement.basestatementHandler; importar org.apache.ibatis.executor.statement.routingStatementHandler; importar org.apache.ibatis.mapping.boundsql; importar org.apache.ibatis.mapping.mapstement; importação oug.apache; mapping.parameterMapping; importar org.apache.ibatis.mapping.parametermode; importar org.apache.ibatis.plugin.interceptor; importar org.apache.ibatis.plugin.intercepts; importar org.apache.ibatis.plugin.invocation; importar ou .apache.ibatis.plugin.plugin; importar org.apache.ibatis.reflection.metaObject; importar org.apache.ibatis.reflection.property.propertyTokenizer; import org.apache.ibatis.script.xmlTags.foreachsqlNode; .ibatis.session.configuration; importar org.apache.ibatis.type.typehandler; importar org.apache.ibatis.type.typehandlerregistry; import com.framework.common.page.impl.page; importar com.framework.common.utils .Reflectutil;/** * * * */ @intercepts ({ @org.apache.ibatis.plugin.signature (type = org.apache.ibatis.executor.statement.statementHandler.class, método = "preparar", args = {Connection.class})}) public class PagePlugin implementa interceptores {private string dialect = ""; private string pagesqlid = ""; @Override Public Object Intercept (Invocation Invocation) lança jogável {if (Invocation.getTarget () Instância de RoutingStatementHandler) {BaseStatementHandler delegate = (BasestatementHandler) RefletUtil. MAPPEDSTATEMENT MAPPEDSTATEMENT = (MAPPEDSTATEMENT) REFLEFFUTIL .getValueByFieldName (Delegate, "MappedStatement"); Página página = página.threadlocal.get (); if (página == null) {página = new Page (); Page.ThreadLocal.Set (Page); } if (mapedstatement.getId (). Matches (".*(" + this.pagesqlid + ") $") && page.getPagesize ()> 0) {boundsql boundsql = delegate.getBoundSql (); Objeto parameterObject = boundSql.getParameToBject (); String sql = boundsql.getSql (); String countSqlid = mapedstatement.getId (). Replaceall (Pagesqlid, "contagem"); MAPPEDSTATEMENT COUNTMAPETSTATEMENT = NULL; if (mapedstatement.getConfiguration (). hasstatement (contagemSqlid)) {countMapDSTATEMENT = MAPPEDSTATEMENT.GETCONFIGURAÇÃO (). } String countSql = null; if (countMappedStatement! = null) {countSql = countMappedStatement.getBoundSql (parameterObject) .getSql (); } else {countSql = "Selecione count (1) de (" + sql + ") t_count"; } int totalCount = 0; Preparado countstmt countstmt = null; ResultSet ResultSet = NULL; tente {conexão de conexão = (conexão) invocação.getargs () [0]; countStmt = Connection.Preparestatement (countSQL); Boundsql countBoundSql = new Boundsql (mapedstatement.getConfiguration (), countsql, boundsql.getParameterMappings (), ParameterObject); setParameters (CountStmt, MappedStatement, CountBoundSQL, ParameterObject); resultSet = countstmt.executeQuery (); if (ResultSet.Next ()) {totalCount = ResultSet.getInt (1); }} catch (Exceção e) {tiro e; } finalmente {try {if (ResultSet! = null) {resultSet.close (); }} finalmente {if (countstmt! = null) {countStmt.close (); }}} página.setTotalCount (totalCount); RefleteTUL.SetValueByFieldName (Boundsql, "SQL", GeratePagesql (SQL, Page)); }} return invocation.proeced (); } / ** * 对 sql 参数 (?) 设值, 参考 org.apache.ibatis.executor.parameter.DefaultParameterHandler * @param ps * @param mapedstatement * @param boundsql * @param parâmetrobject * @THOWSEL SetParameters (preparado PSTatement PS, MappEdStatement MappEdStatement, Boundsql Boundsql, Objeto ParameterObject) lança SqLexception {ErrorContext.Instance (). Atividade ("Definindo parâmetros"). Lista <MeameTerMapping> parameTerMAppings = boundSql.getParameterMAppings (); if (parameTerMAppings! = null) {configuração configuration = mapedstatement.getConfiguration (); TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry (); Metaobject metaObject = parameterObject == null? NULL: Configuration.NewMetaObject (ParameterObject); for (int i = 0; i <parametermappings.size (); i ++) {parameterMapping parameterMapping = parameTerMAppings.get (i); if (parameterMapping.getMode ()! = parametermode.out) {value objeto; String PropertyName = ParameTerMapping.getProperty (); PropertyTokenizer Prop = New PropertyTokenizer (PropertyName); if (parameterObject == null) {value = null; } else if (typeHandlerRegistry.hastypeHandler (parameterObject.getClass ())) {value = parameterObject; } else if (boundsql.hasadditionalParameter (PropertyName)) {value = Boundsql.getAdditionalParameter (PropertyName); } else if (PropertyName.startswith (foreachsqlnode.iTem_prefix) && boundsql.hasadditionalparameter (prop.getName ())) {value = boundsql.getAdditionalParameter (prop.getName ()); if (valor! }} else {value = metaObject == null? null: metaobject.getValue (PropertyName); } TypeHandler typeHandler = parameterMapping.getTypeHandler (); if (typeHandler == null) {tiro novo executoraException ("Não houve TypeHandler encontrado para o parâmetro"+ PropertyName+ "OF Declaration"+ MappEdStatement.getId ()); } typeHandler.setParameter (ps, i + 1, valor, parametermapping.getjdbctype ()); }}}} / ** * 根据数据库方言 , 生成特定的分页 sql * @param sql * @param página * @return * / string privada generatepagesql (string sql, página página) {if (página! = Null && stringils. isNotBlank (dialeto)) {StringBuffer Pagesql = new StringBuffer (); if ("mysql" .equals (dialeto)) {Pagesql.append (sql); PAGESQL.APNEND ("LIMIT"+Page.getCurrentResult ()+","+Page.getPagesize ()); } else if ("oracle" .equals (dialeto)) {Pagesql.append ("selecione * de (selecione tmp_tb. Onde rownum <= "); Pagesql.append (Page.getCurrentResult ()+Page.getPagesize ()); Pagesql.append (") onde row_id> "); Pagesql.append (Page.getCurrentResult ()); } retornar Pagesql.toString (); } else {return sql; }} @Override public Object Plugin (Objeto Target) {return plugin.wrap (Target, este); } @Override public void setProperties (Propriedades Propriedades) {try {if (stringUtils.isEmpty (this.dialect = Properties .getProperty ("dialect"))) {tiro a nova propriedade ("A propriedade dialeta não é encontrada!"); } if (stringUtils.isEmpty (this.Pagesqlid = Propriedades .getProperty ("Pagesqlid"))) {throw New PropertyException ("Páginasqlid não é encontrada!"); }} catch (PropertyException e) {e.printStackTrace (); }}}
3.mybatis 配置文件: mybatis-config.xml
<? xml versão = "1.0" coding = "utf-8"?> <! O name = "Pagesqlid" value = "bypage"/> </plugin> </plugins> </figuration>
4. 分页拦截器
pacote com.framework.common.page.interceptor; importar javax.servlet.http.httpServletRequest; importar javax.servlet.http.httpServletResponse; importação org.apache.commons.lang3.math.NumberTilS; .ModlandView; importar org.springframework.web.servlet.handler.HandlerInterceptorAdapter; importar com.framework.common.page.impl.page;/****14 **/public class PageInterceptor estende o HandlerInterRadapter {@Override Public Void Posthandle ( Solicitação HttpServletRequest, Resposta HttpServLetResponse, manipulador de objetos, ModelAndView ModelAndView) lança exceção {super.PosTHandle (solicitação, resposta, manipulador, modelAndView); Página página = página.threadlocal.get (); if (página! = null) {request.setAttribute ("página", página); } Página.threadlocal.remove (); } @Override public boolean prehandle (solicitação httpServletRequest, resposta httpSertletResponse, manipulador de objeto) lança a exceção {string pagageSize = request.getParameter ("Pagesize"); String pageno = request.getParameter ("pageno"); Página página = new Page (); if (numberItils.isNumber (PageSize)) {Page.SetPagesize (numberUtils.toint (PageSize)); } if (numberUtils.isNumber (pageno)) {Page.SetPageno (numberils.toint (pageno)); } Página.threadlocal.set (página); retornar true; }}
5.Spring 配置
<!- =============================================== ====================== - Carregar arquivo de propriedade - ========================= ============================================ -> <Contexto: Propriedade -PlaceHolder Location = "ClassPath: Application.Properties" /> <bean id = "sqlSessionFactory"> <propriedade name = "DataSource" ref = "DataSource" /> <Nome da propriedade "" ConfigLocation "Value =" ClassPath: MyBatis-Config .xml "/> <propriedade name =" mapperlocations "> <lista> <Value> ClassPath:/com/estrutura/mapper/**/*mapper.xml </value> </list> </propriedade> </bean > <!- ============================================== ======================= - 通过扫描的模式 , 扫描目录下所有的 Dao , 根据对应的 mapper.xml 为其生成代理类 - === =================================================== =============== -> <bean id = "mapperscannerconfigurer"> <propriedade name = "bashepackage" value = "com.framework.dao" /> <nome da propriedade = "ProcessPropertyPlaceHolders" value = "true" /> <nome da propriedade = "sqlSessionFactoryBeanName" value = "sqlSessionFactory" /> </i bean>
6.Springmvc 配置拦截器
Er "PageInterceptor"/> </list> </Property> </bean>