1. 封装分页 Страница 类
Пакет com.framework.common.page.impl; import java.io.serializable; import com.framework.common.page.ipage;/** * * * */public абстрактный класс. Осуществляет Ipage, serializable {/** * */ private static final long serialversionuid = -3623448612757790359l; public static int default_page_size = 20; private int pagesize = default_page_size; частный int currentresult; частная общая страница; Private Int CurrentPage = 1; private int totalCount = -1; public basepage (int currentpage, int pagesize, int totalcount) {this.currentPage = currentPage; this.pageize = pagesize; this.totalcount = totalCount; } public int getTotalCount () {return this.totalcount; } public void cetTotOtalCount (int totalCount) {if (totalCount <0) {this.TotalCount = 0; возвращаться; } 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; возвращаться; } 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; }} вернуть это.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; } вернуть это.currentPage + 1; } public int getCurrentResult () {this.currentResult = ((getPageno () - 1) * getPagesize ()); if (this.currentresult <0) {this.currentresult = 0; } вернуть это.currentResult; } public int getPrepage () {if (isfirstPage ()) {return this.currentPage; } вернуть это.currentPage - 1; }}
пакет com.framework.common.page.impl; import java.util.list;/** * * * *//страница открытого класса Extens BasePage {/** * */Private Static Long Long Serialversionuid = -970177928709377315L; public static threadlocal <GARE> THINELOCAL = NEW THITELOCAL <GAGE> (); частный список <?> Данные; public page () {} public page (int currentPage, int pageSize, int totalCount) {super (CurrentPage, PageSize, TotalCount); } public page (int currentpage, int pagesize, int totalCount, list <?> data) {super (CurrentPage, PageSize, TotalCount); this.data = data; } public list <?> getData () {return data; } public void setData (list <?> data) {this.data = data; }}
2. 封装分页插件
Пакет com.framework.common.page.plugin; import java.sql.connection; импорт java.sql.preparedStatement; импорт java.sql.resultset; импорт java.sql.sqlexcept .Properties; импорт 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.routingStatementHandler; импорт org.apache.ibatis.maping.boundsql; import org.apache.ibatis.mappion.mappedStatement; импорт orgaChe.Apachatis. mapping.parametermapping; import org.apache.ibatis.mapping.parametermode; import org.apache.ibatis.plugin.interceptor; import org.apache.ibatis.plugin.intercepts; импорт org.apache.ibatis.plugin.invocation; импорт org; .apache.ibatis.plugin.plugin; import org.apache.ibatis.reflection.metaobject; импорт org.apache.ibatis.reflect.property.propertytokenizer; импорт org.apache.ibatis.scripting.xmltags.foreachsqlnode; .ibatis.session.configuration; импорт org.apache.ibatis.type.typehandler; import org.apache.ibatis.type.typehandlerregistr .Reflectutil;/** * * * */ @recepts ({ @org.apache.ibatis.plugin.signature (type = org.apache.ibatis.executor.statement.statementhandler.class, method = "preare", args = {Connection.class})}) открытый класс Pageplugin реализует Interceptor {private String dialect = ""; Private String pagesqlid = ""; @Override public Object Intercept (vocation invocation) бросает throwable {if (vocation.getTarget () экземпляр RoutingStatementHandler) {BasestatementHandler delegate = (BasestatementHandler. GetvaluebyfieldName ((RoutingStatementHandler) vocation.getTarget (), "delegate"); MapedStatement MapedStatement = (MapedStatement) Reflectutil .getValuebyfieldName (делегат, "MapedStatement"); Страница страницы = page.threadlocal.get (); if (page == null) {page = new page (); Page.threadlocal.set (page); } if (mapedStatement.getId (). Matches (".*(" + this.pagesqlid + ") $") && page.getPagesize ()> 0) {boundsql boundsql = delegate.getboundsql (); Объект parameterObject = boundsql.getParameterObject (); String sql = boundsql.getsql (); String countsqlid = mapedStatement.getId (). RypeAll (pagesqlid, "count"); MapedStatement CountMampedStatement = null; if (mapedStatement.getConfiguration (). HasStatement (countsqlid)) {countmapedStatement = mapedStatement.getConfiguration (). getMapedStatement (countsQlid); } String countsql = null; if (countmappedStatement! = null) {countsql = countmappedStatement.getBoundSql (parameterObject) .getSql (); } else {countsql = "select count (1) из (" + sql + ") t_count"; } int totalCount = 0; Подготовленное Statatement countstmt = null; Результаты Результаты: null; try {connection connection = (connection) vocation.getargs () [0]; countstmt = connection.prepareStatement (countsql); Boundsql countboundsql = new Boundsql (mapedStatement.getConfiguration (), gountsql, boundsql.getparametermappings (), parameterObject); SetParameters (CountStmt, MapedStatement, CountBoundSQL, ParameterObject); ResultSet = countStmt.ExecUteQuery (); if (resultset.next ()) {totalCount = resultset.getint (1); }} catch (Exception e) {throw e; } наконец {try {if (resultSet! = null) {resultset.close (); }} наконец {if (countstmt! = null) {countstmt.close (); }}} page.setTotalCount (totalCount); Reflectutil.SetValueByfieldName (BoundsQl, «SQL», GERENATEPAGESQL (SQL, PAGE)); }} return vlocation.proceedceed (); } / ** * 对 sql 参数 (?) 设值, 参考 org.apache.ibatis.executor.parameter.defaultparameterhandler * @param ps * @param mapedstatement * @param boundsql * @param parameterobject * @throws sqlexection * / private void SetParameters (PreditStatement PS, MapedStatement MapedStatement, BoundSQL BoundsQL, объект ParameterObject) THROHS SQLEXCEPTION {errorContext.Instance (). Activity («Настройка параметров»). Object (mapedStatement.getParametermap (). getId ();); Список <parametermapping> parametermAppings = boundsql.getParameterMappings (); if (parametermappings! = null) {configuration 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) {значение объекта; 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 (value! = null) {value = configuration.newMetaObject (value) .getValue (PropertyName.subString (prop.getName (). Length ())); }} else {value = metaobject == null? null: metaobject.getValue (PropertyName); } TypeHandler typeHandler = parameterMapping.getTypeHandler (); if (typehandler == null) {бросить новое executorexception («Не было найдено typehandler для параметра»+ PropertyName+ »утверждения»+ mapedStatement.getId ()); } typeHandler.setParameter (ps, i + 1, значение, параметрирование. 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 ("Limit"+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 (") как tmp_tb Где rownum <= "); pagesql.append (page.getCurrentResult ()+page.getPagesize ()); pagesql.append ("), где row_id> "); pagesql.append (page.getCurrentResult ()); } return pagesql.toString (); } else {return sql; }} @Override public Object Plugin (объект Target) {return plugin.wrap (target, this); } @Override public void setProperties (свойства свойств) {try {if (stringUtils.isempty (this.dialect = properties .getProperty ("dialect"))) {бросить новое свойство Exception ("Свойство диалекта не найдено!"); } if (stringUtils.isempty (this.pagesqlid = properties .getProperty ("pagesqlid"))) {Throw New Property Exception ("PageSqlid Property не найдено!"); }} catch (propertyexception e) {e.printstacktrace (); }}}
3.mybatis 配置文件: mybatis-config.xml
<? xml version = "1.0" Encoding = "UTF-8"?> <! Конфигурация doctype public "-// mybatis.org//dtd sql карта config 3.0 // en" "http://mybatis.org/dtd /mybatis-3-config.dtd "> <fincureuration> <blicins> <plagin receptor =" com.framework.common.page.plugin.pageplugin "> <name =" dialect "value =" mysql " /> <свойство name = "pagesqlid" value = "bypage"/> </plagin> </plugins> </configuration>
4. 分页拦截器
пакет com.framework.common.page.interceptor; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import org.apache.commons.lang3.math.numberutils; import org.spramework.web.servlet.servlet.servlet.servlet.servlets. .ModelandView; import org.springframework.web.servlet.handler.handlerInterceptorAdapter; import com.framework.common.page.impl.page;/****14 **/Public PageInterceptor Extends HandlerInterceptorAdapter {@Override public void ( Httpservlectrequest, httpservletresponse response, обработчик объектов, модель и модель модели и вызов). Страница страницы = page.threadlocal.get (); if (page! = null) {request.setattribute ("page", page); } Page.threadlocal.remove (); } @Override public boolean prehandle (запрос httpservletrequest, httpservletresponse, обработчик объекта) Throws Exception {String pageize = request.getParameter ("pagesize"); String pageno = request.getParameter ("pageno"); Страница страницы = новая страница (); if (numberutils.isnumber (pagesize)) {page.setPagesize (numberUtils.toint (pageSize)); } if (numberUtils.isnumber (pageno)) {page.setpageno (numberutils.toint (pageno)); } Page.threadlocal.set (page); вернуть истину; }}
5.spring 配置
<!- ======================================================================= ===================== - Загрузить файл свойств - ========================= ============================================================================= -Поссущество местоположение = "classpath: application.properties" /> <bean id = "sqlSessionFactory"> <name = "dataSource" ref = "dataSource" /> <name = "configlocation" value = "classpath: mybatis-config .xml "/> <name = name =" mapperlocations "> <sist> <dather> classpath:/com/framework/mapper/**/*mapper.xml </value> </list> </properate> </bean > <!- ====================================================================== ===================== - 通过扫描的模式 , 扫描目录下所有的 dao , 根据对应的 mapper.xml 为其生成代理类 - === ============================================================================= ============== -> <bean id = "mapperscannerconfigurer"> <name = "name =" basepackage "value =" com.framework.dao " /> <name =" processpropertyplaceholders " value = "true" /> <name = "sqlSessionFactoryBeanName" value = "sqlSessionFactory" /> < /bean>
6.springmvc 配置拦截器
<!-分页拦截器-> <bean id = "pageInterceptor"> </bean> <!-配置拦截器-> <bean> <name = name = "receptors"> <list> <ref bean = "PageInterceptor"/> </list> </property> </bean>