1. 封装分页 Page 类
package com.framework.common.page.impl; importer java.io.serializable; import com.framework.common.page.ipage; / ** * * * * / public abstrait class Basepage implémente ipage, serializable {/ ** * * / private statique final long 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; privé 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 SettotalCount (int totalCount) {if (totalCount <0) {this.totalCount = 0; retour; } this.totalCount = totalCount; } public BasePage () {} public int getFirStResult () {return (this.currentPage - 1) * this.pageSize; } public void setPageSize (int pagesize) {if (pagesize <0) {this.pagesize = default_page_size; retour; } 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; }} return 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; } return this.currentResult; } public int getPrepage () {if (isFirstPage ()) {return this.currentPage; } return this.currentPage - 1; }}
package com.framework.common.page.impl; Importer java.util.list; / ** * * * * / La page de classe publique étend la haut-base {/ ** * * / private statique finale longue serialVersionUID = -97017928709377315l; public static threadLocal <page> threadLocal = new ThreadLocal <page> (); Liste privée <?> Données; PAMBRE PUBLIQUE () {} PAGE PUBLIQUE (int CurrentPage, int pagesize, int totalCount) {super (currentPage, PageSize, totalCount); } PAGE PUBLIC (int CurrentPage, int pagesize, int totalCount, liste <?> data) {super (currentPage, pagesize, totalCount); this.data = data; } public list <?> getData () {return data; } public void setData (list <?> data) {this.data = data; }}
2. 封装分页插件
package com.framework.common.page.plugin; import java.sql.connection; import java.sql.preparedstatement; import java.sql.resulttset; import java.sql.sqlexception; import java.util.list; import java.utilin .Properties; import javax.xml.bind.propertyException; import org.apache.commons.lang3.stringutils; import org.apache.ibatis.executor.errorcontext; import org.apache.ibatis.executor.executorexception; import org.apache. ibatis.executor.statement.basestatementhandler; import org.apache.ibatis.executor.statement.routingstationhandler; import org.apache.ibatis.mapping.boundsql; import org.apache.ibatis.mapping.maptstatement; import org.apache.ibatis. mapping.parametermapping; import org.apache.ibatis.mapping.parametermode; import org.apache.ibatis.plugin.interceptor; import org.apache.ibatis.plugin.intercepts; import org.apache.ibatis.plugin.invocation; Importer org .apache.ibatis.plugin.plugin; import org.apache.ibatis.reflection.metaObject; import org.apache.ibatis.reflection.property.propertytokizer; import org.apache.ibatis.scripting.xmltags.foreachsqnode; import Org.apache .ibatis.session.configuration; import org.apache.ibatis.type.typehandler; import org.apache.ibatis.type.typehandlergistry; import com.framework.common.page.impl.page; import com.framework.common.utils .ReflectUtil; / ** * * * * / @ intercepts ({@ org.apache.ibatis.plugin.signature (type = org.apache.ibatis.executor.statement.statementhandler.class, méthode = "prépare", args = {Connection.class})}) La classe publique PagePlugin implémente interceptor {private String dialect = ""; chaîne privée pagesqlid = ""; @Override Public Object Intercept (Invocation Invocation) lance Throwsable {if (invocation.getTarget () instanceof routingStationHandler) {BasestationHandler Delegate = (BasestatementHandler) ReflectUtil .getValueByFieldName ((RoutingStatementHandler) invocation.getTarget (), "Delegate"); MaptedStatement MapStStatement = (MapsageStatement) RéflectUtil .getValueByFieldName (Delegate, "MaptedStatement"); Page page = page.threadlocal.get (); if (page == null) {page = new page (); Page.threadlocal.set (page); } if (mappedStAment.getId (). Matches (". * (" + this.pagesqlid + ") $") && page.getPageSize ()> 0) {boundsql boundsql = delegate.getBoundSQL (); Object ParameterObject = boundsql.getParameterObject (); String sql = boundsql.getsql (); String CountSQLID = MAPPEDSATATION.GETID (). RempaceALL (PagesQLid, "Count"); MaptedStatement CountMaptStatement = NULL; if (mappedstatement.getConfiguration (). Hasstatement (countSQLID)) {countMaptStatement = mappedStatement.getConfiguration (). getMaptStatement (countSQLid); } Chaîne countql = null; if (countMaptStatement! = null) {countSQL = countmaptStatement.getBoundSQL (ParameterObject) .getsql (); } else {countSql = "select count (1) from (" + sql + ") t_count"; } int totalCount = 0; PRÉPAYÉSATATION COUNTSTMT = NULL; ResultSet resultSet = null; try {connection connection = (connection) invocation.getargs () [0]; countstmt = connection.preparestatement (countSQL); BOUNDSQL COUNTBOUNDSQL = NOUVEAU BOURNSQL (MAPPEDSATATION.GETCONFIGURATION (), COUNTSQL, BOUNDSQL.GETPARAMETERMAppings (), ParameterObject); setParameters (countstmt, maptedstatement, countboundsql, parameterObject); resultSet = countstmt.executequery (); if (resultSet.Next ()) {totalCount = resultSet.getInt (1); }} catch (exception e) {throw e; } enfin {try {if (resultSet! = null) {resultSet.close (); }} enfin {if (countstmt! = null) {countstmt.close (); }}} page.setTotalCount (totalCount); ReflectUtil.setValueByFieldName (BoundsQL, "SQL", GeneratePagesQL (SQL, Page)); }} return invocation.proceed (); } / ** * 对 sql 参数 (?) 设值, 参考 org.apache.ibatis.executor.parameter.defaultParameterHandler * @param ps * @param mappedstatement * @param boundsql * @param paramètreOrbject * @throws sqlexception * / private Void * setParameters (préparéStatement PS, MapStaTATION MAPPEDSATATION, BOUNDSQL BOUNDSQL, Object ParamètreObject) lève SQELLEXception {errorContext.instance (). Activity ("Setting Paramètres"). List <paramètres de paramètres> Paramètres de paramètres = boundsql.getParameTermAppings (); if (ParameTermAppings! = null) {Configuration Configuration = mappedStatement.getConfiguration (); TypeHandlerRegistry TypeHandlerRegistry = configuration.getTypeHandlerRegistry (); MetaObject metaObject = ParameterObject == null? null: configuration.newMetaObject (ParameterObject); for (int i = 0; i <paramettermappings.size (); i ++) {paramètre paramètre paramètre = paramètres.get (i); if (ParameTerpapping.getMode ()! = ParameTermode.out) {Valeur d'objet; 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 (propriétéName)) {value = boundsql.getAdditionalParameter (propriétéName); } else if (propriétéName.startswith (foreachsqlnode.item_prefix) && boundsql.hasadditionalParameter (prop.getName ())) {value = boundsql.getAdditionalPaMeter (prop.getName ()); if (value! = null) {value = configuration.newMetaObject (value) .getValue (propriétéName.SubString (prop.getName (). Length ())); }} else {value = metaObject == null? null: metaObject.getValue (PropertyName); } TypeHandler typeHandler = ParameterApping.getTypeHandler (); if (typeHandler == NULL) {Throw New Executorexception ("Il n'y avait aucun type Handleur trouvé pour le paramètre" + propriétéName + "of Statement" + maptedStatement.getId ()); } typehandler.setParameter (ps, i + 1, valeur, paramètre.getjdbcType ()); }}}} / ** * 根据数据库方言 , 生成特定的分页 sql * @param sql * @param page * @return * / private String generatePagesql (String sql, page page) {if (page! = Null && StringUtils. isNotBlank (dialect)) {stringBuffer pagesql = new StringBuffer (); if ("mysql" .equals (dialect)) {pagesql.append (sql); pagesql.append ("limite" + page.getCurrentResult () + "," + page.getPageSize ()); } else if ("Oracle" .Equals (dialect)) {pagesql.append ("SELECT * FROM (SELECT TMP_TB. *, Rownum Row_id From ("); pagesql.append (sql); pagesql.append (") en tant que tmp_tb Où Rownum <= "); pagesql.append (page.getCurrentResult () + page.getPageSize ()); pagesql.append (") où row_id> "); pagesql.append (page.getCurrentResult ()); } return pagesql.toString (); } else {return sql; }} @Override Public Object Plugin (objet Target) {return plugin.wrap (Target, This); } @Override public void setProperties (Properties Properties) {try {if (stringUtils.isempty (this.dialect = properties .getProperty ("dialect"))) {throw newprestException ("La propriété du dialect n'est pas trouvée!"); } if (stringUtils.isempty (this.pagesqlid = properties .getProperty ("pagesqlid"))) {throw new PropertyException ("la propriété pagesqlid n'est pas trouvée!"); }} catch (PropertyException e) {e.printStackTrace (); }}}
3.Mybatis 配置文件: Mybatis-Config.xml
<? xml version = "1.0" Encoding = "utf-8"?> <! Doctype Configuration public "- // mybatis.org//dtd sql map config 3.0 // en" "http://mybatis.org/dtd /mybatis-3-Config.dtd "> <filony> <Glugins> <plugin interceptor =" com.framework.common.page.plugin.pageplugin "> <propriété name =" dialect "value =" mysql "/> <propriété name = "pagesqlid" value = "byPage" /> </ plugin> </glugins> </figuration>
4. 分页拦截器
package com.framework.common.page.interceptor; import javax.servlet.http.httpservletRequest; import javax.servlet.http.httpservletResponse; import org.apache.commons.lang3.math.numberUtils; import org.springframeworkwork.web.sservlet .ModelandView; import org.springframework.web.servlet.handler.handlerInterceptorAdapter; import com.framework.common.page.impl.page; / *** * 14 ** / classe publique Page Interceptor étend HandlerInterceptorAdapter {@Override public Void Posthandle ( HttpServLetRequest Request, HttpServletResponse Response, Object Handler, ModelAndView ModelAndView) lève une exception {super.poSthandle (request, réponse, gestionnaire, modelandView); Page page = page.threadlocal.get (); if (page! = null) {request.setAttribute ("page", page); } Page.threadlocal.remove (); } @Override public boolean prehandle (httpsservletRequest request, httpsservletResponse réponse, objet handler) lève exception {String pagesize = request.getParameter ("pagesize"); String pageno = request.getParameter ("pageno"); Page page = new page (); if (NumberUtils.isNumber (pagesize)) {page.setPageSize (nombreUtils.Toint (pagesize)); } if (NumberUtils.isnumber (pageno)) {page.setpageno (nombreutils.toint (pageno)); } Page.threadlocal.set (page); Retour Vrai; }}
5.Spring 配置
<! - ===========================================. ===================== - Fichier de propriété de chargement - ====================== ==========================================. -PlaceHolder location = "classpath: application.properties" /> <bean id = "sqlSessionFactory"> <propriété name = "dataSource" ref = "dataSource" /> <propriété name = "configLocation" value = "classpath: mybatis-config .xml "/> <propriété name =" Mappenlocations "> <sist> <value> classpath: / com / framework / mapper / ** / * mapper.xml </value> </sist> </ propriété> </ bean > <! - =========================================. ====================== - 通过扫描的模式 , 扫描目录下所有的 Dao , 根据对应的 Mappe ==============================================. ============== -> <bean id = "MAPPERScannerConfigurer"> <propriété name = "basepackage" value = "com.framework.dao" /> <propriété name = "ProcessPropertyPlaceHolders" value = "true" /> <propriété name = "sqlSessionFactoryBeanName" value = "sqlSessionFactory" /> </ank>
6.Springmvc 配置拦截器
<! - 分页拦截器 -> <bean id = "PageInterceptor"> </anEn> <! - 配置拦截器 -> <anEn> <propriété name = "intercepteurs"> <s list> <ref bean = "PageInterceptor" /> </ list> </ propriété> </ban>