1. 封装分页 Seite 类
Paket com.framework.common.page.impl; importieren java.io.serializable; import com.framework.common.page.ipage;/** * * * */public abstrakt */ Private statische endgültige lange 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; privat int totalCount = -1; public basepage (int currentPage, int pageSize, int totalCount) {this.currentPage = currentPage; this.PageSize = pageSize; this.totalcount = TotalCount; } public int getTotalCount () {retot this.totalCount; } public void settotalCount (int totalCount) {if (TotalCount <0) {this.totAlcount = 0; zurückkehren; } 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; zurückkehren; } this.pageSize = pageSize; } public int getTotalPage () {if (this.totalPage <= 0) {this.totalpage = (this.totalCount / this.pageSize); if ((this.totalpage == 0) || (totalCount % this.pageSize! = 0)) {this.totalPage += 1; }} retotal.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; }}
Paket com.framework.common.page.impl; Import Java.util.list;/** * * * * */public Class erweitert Basepage {/** * */private statische endgültige long serialversionuid = -97017792870937315l; public static threadLocal <Page> ThreadLocal = new ThreadLocal <page> (); private Liste <?> Daten; public page () {} public page (int currentPage, int pageSize, int totalCount) {Super (currentPage, pageSize, TotalCount); } öffentliche Seite (int CurrentPage, int pageSize, int TotalCount, Liste <?> Daten) {Super (currentPage, pageSize, TotalCount); this.data = Daten; } public List <?> getData () {returndaten; } public void setData (Liste <?> Daten) {this.data = data; }}
2. 封装分页插件
Paket com.framework.common.page.plugin; import Java.sql.Connection; Import Java.SQL.PreparedStatement; Import Java.sql.resultset; Importieren Sie Java.Sql.SQL.SqLexception; Import Java.util.list; .Properties; importieren javax.xml.bind.propertyException; import org.apache.commons.lang3.stringutils; import org.apache.ibatis.executor.ErrorContext; import org.apache.ibatis.executor.executorexception; importieren org.apache. ibatis.executor.statement.basestatementHandler; import org.apache.ibatis.executor.statement.routingStatementHandler; import org.apache.ibatis.mapping.boundsql; import org. maping.parametermaping; import org.apache.ibatis.mapping.parametermode; import org.apache.ibatis.plugin.interceptor; import org.apache.ibatis.plugin.intercepts; importieren org.apache.ibatis.Plugin.invocation; .apache.ibatis.plugin.plugin; import org.apache.ibatis.reflection.metaObject; import org.apache.ibatis.reflection.property.propertytokenizer; import org.apache.ibatis.script.xmltags.foreachsqlnode; oderg.apache oderg.apache; .ibatis.session.configuration; import org.apache.ibatis.type.typeHandler; import org.apache.ibatis.type.typeHandlerregistry; import com.framework.common.page.impl.page; com.framework.common.utils.utils .ReflectUtil;/** * * * */ @intercepts ({ @org.apache.ibatis.plugin.signature (type = org.apache.ibatis.executor.statement.statementHandler.class, method = "vorbereiten", args = {Connection.class})}) public class pagePlugin implementiert Interceptor {private String dialect = ""; private String pagesqlid = ""; @Override Public Object Intercept (Invocation Invocation) löst Throwable {if (invocation.gettarget () Instanz von RoutingStatementHandler) {BasestatementHandler delegate = (BasestatementHandler) refledUtil .getValuebyfieldname ((RoutingStatementHandler) -Vocation.GTETTARGet (), "),"), "),"), "),"). MADKAPTSETIement MADCDSTATEMENTS = (MADKPITTATEMENT) Reflectil .getValuebyfieldName (Delegierter, "Kartentatement"); Seite page = page.threadlocal.get (); if (page == null) {page = new Page (); Page.threadlocal.set (Seite); } if (mappedStatement.getId (). Übereinstimmung (".*(" + this.pagesqlid + ") $") && page.getPageSize ()> 0) {boundSQL bodernsql = delegate.getBoundSql (); Object ParameterObject = bodernsql.getParameterObject (); String sql = bodensql.getSQL (); String countSQLID = MADPDStatement.getId (). Ersatz (Pagesqlid, "count"); MADCPDStatement CountMappedStatement = NULL; if (mapPedStatement.getConfiguration (). HasStatement (countSQLID)) {countMappedStatement = mapPedStatement.getConfiguration (). } String countSQL = null; if (countMappedStatement! } else {countSQL = "Wählen Sie count (1) aus (" + sql + ") t_count"; } int totalCount = 0; PrepedStatement countstmt = null; ResultSet resultSet = null; try {Connection Connection = (Connection) Invocation.getargs () [0]; countstmt = Connection.preparestatement (countSQL); BoundSQL countBoundSQL = new boundSQL (mappedStatement.getConfiguration (), countSQL, boundSQL.getParameterMappings (), parameterObject); setParameters (countstmt, kartonisch, countboundSQL, parameterObject); resultSet = countstmt.executeQuery (); if (resultSet.Next ()) {TotalCount = resultSet.getInt (1); }} catch (Ausnahme e) {throw e; } endlich {try {if (resultSet! = null) {resultSet.close (); }} endlich {if (countstmt! = null) {countstmt.close (); }}} page.settotalCount (TotalCount); ReflectUtil.setValuebyfieldname (boundSQL, "SQL", GeneratePagesql (SQL, Page)); }} return Invocation.Procece (); } / ** * 对 sql 参数 (?) 设值, 参考 org.apache.ibatis.executor.parameter.DefaultParameterHandler * @param ps * @param mappedStatement * @param bodensql * @param parameterObject * @throws SQLEXception * / privat void void void setParameters (prepectStatement ps, kartierstatement kartierstatement, bodernsql boundSQL, Object ParameterObject) löscht sqlexception {errorContext.instance (). Aktivität ("Einstellparameter"). Liste <PARAMETERMAPPING> ParameterMappings = bodernSQL.getParametermappings (); if (parameterMappings! = null) {configuration configuration = mappedStatement.getConfiguration (); TypeHandlerregistry typeHandlerregistry = configuration.gettypeHandlerregistry (); MetaObject metaObject = parameterObject == null? null: configuration.newmetaObject (parameterObject); für (int i = 0; i <parameterMappings.size (); i ++) {parameterMapping parametermaping = parameterMappings.get (i); if (parametermaping.getMode ()! = parametermode.out) {Objektwert; String PropertyName = parametermaping.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 = bandsql.getAdDitionalParameter (PropertyName); } else if (PropertyName.Startswith (foreachSQlnode.item_prefix) && boundsql.hasadditionalParameter (prop.getName ())) {value = boundsql.getAditionalParameter (prop.getName ()); if (value! }} else {value = metaObject == null? NULL: metaObject.getValue (Eigentumsname); } TypeHandler typeHandler = parameterMaping.gettypeHandler (); if (typeHandler == null) {throw New executorexception ("Es wurde kein TypeHandler für den Parameter gefunden"+ PropertyName+ "der Anweisung"+ mappedStatement.getId ()); } typeHandler.setParameter (ps, i + 1, Wert, parametermaping.getJdbcType ()); }}}} / ** * 根据数据库方言 , 生成特定的分页 SQL * @param SQL * @param Seite * @return * / private String generatePagesql (String SQL, Seite) {if (Seite! = Null && Stringutils. isnotblank (Dialekt)) {stringBuffer pagesql = new StringBuffer (); if ("mysql" .equals (Dialekt)) {pagesql.Append (SQL); pagesql.append ("limit"+page.getCurrentresult ()+","+page.getPageSize ()); } else if ("oracle" .equals (Dialekt)) {pagesql.append ("auswählen * aus (auswählen tmp_tb. *, rownum row_id from ("); pagesql.append (SQL); Pagesql.append (") als tmp_tbb Wobei Rownum <= "); pagesql.Append (page.getCurrentresult ()+page.getPageSize ()); Pagesql.Append (") wobei row_id> "); PAGESQL.Append (page.getCurrentresult ()); } return pagesql.toString (); } else {return SQL; }} @Override öffentliches Objekt -Plugin (Objektziel) {return plugin.wrap (target, this); } @Override public void setProperties (Eigenschaften Eigenschaften) {try {if (stringutils.isempty (this.dialect = properties .getProperty ("Dialekt"))) {Neue PropertyException ("Dialekt -Eigenschaft wird nicht gefunden!"); } if (stringutils.isempty (this.pagesqlid = properties .getProperty ("pagesqlid"))) {wurf new PropertyException ("Pagesqlid -Eigenschaft wird nicht gefunden!"); }} catch (PropertyException e) {e.printstacktrace (); }}}
3.Mybatis 配置文件: mybatis-config.xml
<? /mybatis-3-config.dtd "> <configuration> <plugins> <plugin interceptor =" com.framework name = "pagesqlid" value = "bypage"/> </plugin> </plugins> </configuration>
4. 分页拦截器
Paket com.framework.common.page.Interceptor; import javax.servlet.http.httpsersquest; import Javax.servlet.http.httpServletResponse; import org.apache.commons.lang3.math.numberutils; .ModelandView; import org.springframework.web.servlet.handler.handlerInterceptoradapter; importieren HttpServletRequest -Anforderung, httpServletResponse -Antwort, Objekthandler, modelAndView modelAndView) löst eine Ausnahme aus (Super.Posthandle (Anfrage, Antwort, Handler, ModelAndView); Seite page = page.threadlocal.get (); if (page! = null) {request.setAttribute ("Seite", Seite); } Page.threadlocal.remove (); } @Override public boolean prehandle (httpServletRequest -Anforderung, httpServletResponse -Antwort, Objekthandler) löst eine Ausnahme aus {String pageSize = request.getParameter ("pageSize"); String pageno = request.getParameter ("pageno"); Seite Seite = new Page (); if (numnUtils.isNumber (pageSize)) {page.setPageSize (numnUtils.toint (pageSize)); } if (numnUtils.isNumber (pageno)) {page.setpageno (numnUtils.toint (pageno)); } Page.threadlocal.set (Seite); zurückkehren; }}
5. Spring 配置
<!- ================================================= ===================== - Load property file - ======================== =============ieben -Placeholder location = "classPath: application.Properties" /> <bean id = " .xml "/> <Eigenschaft name =" mapperlocations "> <list> <wert> classPath:/com/Framework/Mapper/**/*mapper.xml </value> </list> </property> </bean > <!- =============================================== ====================== - 通过扫描的模式 , 扫描目录下所有的 Dao , 根据对应的 mapper.xml 为其生成代理类 - === ====================================================== =============== -> <bean id = "mapperscannerConFigurer"> <Eigenschaft name = "Basepackage" value = "com.framework.dao" /> <Property name = "ProcessPropertyPlacePlaceolder" value = "true" /> <Eigenschaft name = "sqlSessionFactoryBeanname" value = "
6.springmvc 配置拦截器
<!-分页拦截器-> <bean id = "pageInterceptor"> </bean> <!-配置拦截器-> <bean> <Property name = "interceptors"> <list> <ref bean = "pageInterceptor"/> </list> </property> </bean>