1.封装分页ページ类
パッケージcom.framework.common.page.impl; import java.io.serializable; Import com.framework.common.page.ipage;/ * * * * */public抽象クラスのベースページはipage、serializable {/** * * */ private static final long serialversionuid = -362344861275790359l; public static int default_page_size = 20; private int pagesize = default_page_size; private int currentResult;プライベートINT TotalPage; private int currentPage = 1; private int totalcount = -1;パブリックベースページ(int currentPage、int pagesize、int totalcount){this.currentPage = currentPage; this.pagesize = pagesize; this.totalcount = totalcount; } public int gettotalcount(){this.totalcount; } public void settoTotalCount(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; }} 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; } this.currentPage + 1; } public int getCurrentResult(){this.currentResult =((getPageno()-1) * getPagesize()); if(this.currentresult <0){this.currentresult = 0; } this.currentresult; } public int getPrepage(){if(isfirstpage()){return this.currentpage; } this.currentPage -1; }}
パッケージcom.framework.common.page.impl; import java.util.list;/** * * * */public classページはベースページ{/** * * */private static final long serialversionuid = -97017928709377315l; public static threadlocal <page> threadlocal = new threadlocal <page>();プライベートリスト<?>データ; 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; Import java.sql.preparedStatement; Import java.sql.Resultset; Import java.sql.sqlecception; Import Java.util.list; Import Java.util .properties; Import javax.xml.bind.propertyexception; import org.apache.commons.lang3.stringutils; Import org.apache.ibatis.executor.errorcontext; Import org.apache.ibatis.executor.executorexception; Immort org.apache。 ibatis.executor.statement.basestatementhandler; Import org.apache.ibatis.executor.statement.routingstatementementhandler; Import org.apache.ibatis.mapping.boundsql; Import org.apache.ibatis.mapping.mapptatement; import org.apach.ibatis; mapping.parametermapping; Import org.apache.ibatis.mapping.parametermode; Import org.apache.ibatis.plugin.interceptor; Import org.apache.ibatis.plugin.plugin.plugin.intecte; .apache.ibatis.plugin.plugin; import org.apache.ibatis.reflection.metaobject; import org.apache.ibatis.reflection.property.pache.apache.ibatis.scripting.xmltags.foreachsqlnode; Immort org.apache .ibatis.session.configuration; Import org.apache.ibatis.type.typehandler; Import org.apache.ibatis.type.typehandlerregistry; 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、method = "prepare"、args = {connection.class})})public class pageplugin Interceptor {private string dialect = "";プライベート文字列pagesqlid = ""; @Overrideパブリックオブジェクトインターセプト(Invocation Invocation)スロー可能{if(Invocation.getTarget()InstanceOf RoutingStatementHandler){BaseStateMentementHandler Delegate =(BaseStateMentementHandler)Reflectil .GetValueByFieldName((RoutingStatementHandler)Invocation.GetTarget()、 "Delegate"); mappedStatement MappedStatement =(MappedStatement)refrectil .getValueByFieldName(Delegate、 "MappedStatement");ページページ= page.threadlocal.get(); if(page == null){page = new page(); page.threadlocal.set(page); } if(mappedStatement.getId()。matches( "。*(" + this.pagesqlid + ")")&& page.getPagesize()> 0){boundsql boundsql = delegate.getBoundsql(); object parameterObject = bundsql.getParameterObject();文字列sql = bundsql.getsql(); string countsqlid = mappedStatement.getId()。fallingeall(pagesqlid、 "count"); mappedStatement countMappedStatement = null; if(mappedstatement.getConfiguration()。hasStatement(countSqlid)){countMappedStatement = mappedStatement.getConfiguration()。getMappStatement(countSQLID); }文字列countSql = null; if(countMappedStatement!= null){countSql = countMappedStatement.getBoundSQL(parameterObject).getSql(); } else {countSql = "(" + sql + ")t_count"からcount(1)を選択(1)を選択します。 } int totalcount = 0; preatedStatement countStmt = null; resultet resultset = null; try {connection connection =(connection)rivocation.getargs()[0]; countStmt = connection.preparestatement(countsql); BoundsQl countBoundSql = new BoundSql(MappedStatement.GetConfiguration()、CountSQL、BoundSQL.GetParameterMAppings()、ParameterObject); SetParameters(countStmt、MappedStatement、CountBoundSQL、ParameterObject); resultSet = countstmt.executequery(); if(resultset.next()){totalcount = resultset.getint(1); }} catch(例外e){shrow e; }最後に{try {if(resultet!= null){resultSet.close(); }}最後に{if(countstmt!= null){countstmt.close(); }}} page.settotalcount(totalcount); Reflectutil.setValueByfieldName(BoundSql、 "SQL"、GeneratePagesQl(SQL、Page)); }} return ichvocation.proceed(); } / ** *对sql参数(?)设值、参考org.apache.ibatis.executor.parameter.defaultparametaryetarhandler * @param ps * @param mappedstatement * @param boundsql * @param parameterobject * @throws sqlecception * / private viod SetParameters(preatedStatement PS、MappedStatement MappedStatement、BoundsQl BoundsQl、Object ParameterObject)Throws sqlexception {errorcontext.instance()。アクティビティ(「パラメーターの設定」)。リスト<パラメーターマッピング> parametermappings = bundsql.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 <parametermappings.size(); i ++){parametermapping parametermapping = parametermappings.get(i); if(parametermapping.getMode()!= parametermode.out){object値; 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)&& bundsql.hasadditionalParameter(prop.getName())){value = boundsql.getAdtionalParameter(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){show new executorexception( "statement"+ mappedstatement.getid())のパラメーター "+ propertyname+"には型型ハンドラーが見つかりませんでした。 } typehandler.setParameter(ps、i + 1、value、parametermapping.getjdbctype()); }}}} / ** *根据数据库方言、生成特定的分页sql * @param sql * @param page * @return * / private string generatepagesql(string sql、page){if(page!= null && stringutils。 isnotblank(方言)){stringbuffer pagesql = new StringBuffer(); if( "mysql" .equals(方言)){pagesql.append(sql); pagesql.append( "lime"+page.getCurrentResult()+"、"+page.getPagesize()); } else if( "oracle" .equals(dierect)){pagesql.append( "select * from(select tmp_tb。 *、rownum row_id from("); pagesql.append(sql); pagesql.append( ")as tmp_tb rownum <= "); pagesql.append(page.getCurrentResult()+page.getPagesize()); pagesql.append(")where row_id> "); pagesql.append(page.getCurrentResult()); } pagesql.toString()を返します。 } else {return sql; }} @Override public Object Plugin(Object Target){return plugin.wrap(target、this); } @Override public void setProperties(Properties Properties){try {if(stringutils.isempty(this.dialect = properties .getProperty( "dierect"))){throw new PropertyException( "Dierect Property is not vund!"); } if(stringutils.isempty(this.pagesqlid = properties .getProperty( "pagesqlid"))){throw new PropertyException( "PagesQLidプロパティは見つかりません!"); }} catch(propertyException e){e.printstacktrace(); }}}
3.mybatis配置文件:mybatis-config.xml
<?xml version = "1.0" encoding = "utf-8"?> <!doctype構成public " - // mybatis.org//dtd sql map config 3.0 // en" "http://mybatis.org/dtd /mybatis-3-config.dtd "> <configuration> <plugins> <plagin interceptor =" com.framework.common.page.page.plugin.pageplugin "> <プロパティ名="方言 "値=" mysql " /> <プロパティname = "pagesqlid" value = "bypage"/> </plugin> </plugins> </configuration>
4.分页拦截器
パッケージcom.framework.common.page.interceptor; import javax.servlet.http.httpservletrequest; Import javax.servlet.servlet.htttpservletresponse; Import org.apache.commons.lang3.math.numbutils; org.springframework.weblet .modelandview; Import org.springframework.web.servlet.handler.handlerinterceptoradapter; Import com.framework.common.page.impl.page;/****14 **/public class pageinterceptor拡張ハンドラーインテッセプセラダプター{@Override public void poshandle( httpservletRequestリクエスト、httpservletResponse応答、オブジェクトハンドラー、ModelandView ModelandView)例外{super.posthandle(request、response、handler、modelandview);ページページ= page.threadlocal.get(); if(page!= null){request.setattribute( "page"、page); } page.threadlocal.remove(); } @Override public boolean prehandle(httpservletrequest request、httpservletresponse応答、オブジェクトハンドラー)スロー{string pagesize = request.getparameter( "pagesize"); string pageno = request.getParameter( "pageno");ページページ= new Page(); if(numberutils.isnumber(pagesize)){page.setPagesize(numberutils.toint(pagesize)); } if(numberutils.isnumber(pageno)){page.setpageno(numberutils.toint(pageno)); } page.threadlocal.set(page); trueを返します。 }}
5.SPRING配置
<! - ====================================================== ========================== - プロパティファイルをロード - =================== ===================================== -placholder location = "classpath:application.properties" /> <bean id = "sqlsessionfactory"> <プロパティ名= "dataSource" ref = "dataSource" /> <プロパティ名= "configlocation" value = "classpath:mybatis-configigig .xml "/> <プロパティ名=" mapperlocations "> <list> <value> classpath:/com/mapper/**/*mapper.xml </value> </list> </property> </bean > <! - ======================================================= ==================== =========================================================== ============== --><bean id="mapperScannerConfigurer"> <property name="basePackage" value="com.framework.dao" /> <property name="processPropertyPlaceHolders" value = "true" /> <プロパティ名= "sqlsessionfactorybeanname" value = "sqlsessionfactory" /> < /bean>
6.SPRINGMVC配置拦截器
<! - 分页拦截器 - > <bean id = "pageInterceptor"> </bean> <! - > <bean> <プロパティ名= "インターセプター"> <リスト> <ref bean = 「PageInterceptor」/> </list> </property> </bean>