プロジェクトの開始時に、MyBatisのページングを使用する必要がありました。オンラインで多くのプラグインを読みました。実際、実装の原則は基本的に同じですが、それらのほとんどはコードのみを与え、不完全な注釈を持っています。そこで、私は多くの記事を参照しました(各記事は小さなコードを盗み、自分のコードを評価し、それを半普及させます)、そして私はプロジェクトに適したページングプラグインを模倣して書きました。これ以上苦労せずに、コードをアップロードしました。ほとんどの記事と比較して、注釈は非常に完全です。
最も重要なインターセプター
パッケージcom.dnkx.interceptor; Java.sql。*をインポートします。 java.util.hashmapをインポートします。 java.util.propertiesをインポートします。 org.apache.ibatis.executor.resultset.resultsethandlerをインポートします。 org.apache.ibatis.executor.statement.statementhandlerをインポートします。 Import org.apache.ibatis.mapping.boundsql; Import org.apache.ibatis.mapping.mappedStatement; org.apache.ibatis.plugin.interceptorをインポートします。 org.apache.ibatis.plugin.interceptsをインポートします。 Import org.apache.ibatis.plugin.invocation; org.apache.ibatis.plugin.pluginをインポートします。 org.apache.ibatis.plugin.signatureをインポートします。 org.apache.ibatis.reflection.metaobjectをインポートします。 org.apache.ibatis.reflection.systemmetaobjectをインポートします。 com.dnkx.pojo.pageをインポートします。 /** * *ページネーションインターセプター。ページングクエリを必要とする操作をインターセプトしてから、それらをページングするために使用されます。 * MyBatisページングの原理は、インターセプターを使用して実装されます。 * JDBCを使用してデータベースを動作させるには、対応するステートメントオブジェクトが必要です。 MyBatisがSQLステートメントを実行する前に、SQLステートメントを含むステートメントオブジェクトを生成し、対応するSQLステートメント*はステートメントの前に生成されるため、ステートメントを生成する前にステートメントを生成するために使用されるSQLステートメントから始めることができます。 MyBatisステートメントでは、RoutingStatementHandlerオブジェクトの *準備方法によって生成されます。したがって、インターセプターを使用してMyBatisページングを実装するためのアイデアの1つは、StatementHandlerインターフェイスの準備方法をインターセプトし、SQLステートメントをインターセプターメソッドの対応するページネーションクエリSQLステートメントに変更し、 * StatementHandlerオブジェクトの準備方法を呼び出すことです。 *ページネーションの場合、インターセプターで行う必要がある操作の1つは、現在の条件を満たすレコードの総数をカウントすることです。これは、元のSQLステートメントを取得し、対応する統計ステートメントに変更し、MyBatisカプセル化されたパラメーターと設定 *パラメーターを使用してSQLステートメントのパラメーターを置き換えることです。次に、レコードの数をクエリするSQLステートメントが実行され、レコードの総数がカウントされます。 **プラグインで使用できるいくつかのクラスの説明:* MetaObject:プロパティ値を返すオブジェクトに基づいてMyBatisが提供するクラス* BoundSQL:これで、SQLを実行するパラメーターを使用して、SQLマッピングステートメントを実行するために使用することができます。 MyBatisメモリページング。 * ParameterHandler:SQLに表示される値を置き換えるためにMyBatisで使用されます。 * * @author li xiaogui 2016年11月9日10:59:04 */ @intercepts({@signature(type = statementhandler.class、method = "prepare"、args = {connection.class})、 @signature(type = resultesandler.class、method = "handleresceptets = {handleresultes" Interceptor {//ページングキーワードプライベート静的な最終文字列select_id = "page"; //プラグインによって実行されるコードは、元の方法を置き換え、最も重要なインターセプト@Overrideパブリックオブジェクトインターセプト(Invocation Invocation)Throwableを書き直します{if(Invocation.getTarget()Instance of StatementHandler){//ここでは、クエリメソッドにページが含まれている場合、他のメソッドのページングが含まれます。 MetaObject MetaObject = SystemMetaObject.ForObject(StatementHandler); mappedStatement MappedStatement =(MappedStatement)MetaObject.getValue( "Delegate.Mapptatement"); string sequired = mappedstatement.getId(); string methodname = selectid.substring(selectid.lastindexof( "。")+1).tolowercase(); //ページが含まれているかどうかを判断するには、sql if(methorname.contains(select_id)){bundsql bundsql =(bundsql)metaobject.getValue( "Delegate.BoundSql");を取得します。 //ページネーションパラメーターは、parameterObjectパラメーターオブジェクト文字列sql = boundsql.getSql()のプロパティです。 System.out.println( "get sql:"+sql); hashmap <string、object> map =(hashmap <string、object>)(boundsql.getParameterObject()); //ページpage =(page)(boundsql.getParameterObject());ページページ=(ページ)Map.get( "Page"); // sql string countsql = concatcountsql(sql);文字列pagesql = concatpagesql(sql、page); // system.out.println( "count count sql:"+countsql); system.out.println( "select select sql:"+pagesql);接続接続=(connection)rikocation.getargs()[0]; preatedStatement countStmt = null;結果rs = null; int totalcount = 0; try {countstmt = connection.preparestatement(countSQL); rs = countstmt.executequery(); if(rs.next()){totalcount = rs.getint(1); }} catch(sqlexception e){system.out.println( "この例外を無視する"+e); }最後に{try {rs.close(); countstmt.close(); } catch(sqlexception e){system.out.println( "この例外を無視する"+e); }} metaobject.setValue( "Delegate.BoundSQL.SQL"、PagesQl); // bind count page.setnumcount(totalcount); }} return ichvocation.proceed(); } // type StatementHandlerをインターセプトし、プラグインメソッド@Overrideパブリックオブジェクトプラグイン(オブジェクトターゲット){if(Target Instanceof StatementHandler){return plugin.wrap(target、this); } else {return target; }} @Override public void setProperties(プロパティプロパティ){} // sql public string concatcountsql(string sql){// stringbuffer sb = new StringBuffer( "Select count(*)from"); /*SQL=SQL.TOLOWERCASE(); if(sql.lastindexof( "order")> sql.lastindexof( ")")){sb.append(sql.substring(sql.indexof( "from")+4、sql.lastindexof( "order"))); } else {sb.append(sql.substring(sql.indexof( "from")+4)); }*/ stringbuffer sb = new StringBuffer(); sql = sql.tolowercase(); if(sql.lastindexof( "order")> 0){sql = sql.substring(0、sql.indexof( "order")); } sb.append( "(*)from("+sql+")tmp"); return sb.tostring(); } public string concatpagesql(string sql、ページページ){stringbuffer sb = new StringBuffer(); sb.append(sql); sb.append( "lime").append(page.getPageBegin())。append( "、").append(page.getPagesize()); return sb.tostring(); }}ページクラス[Java] Plain CopyPackage com.dnkx.pojo; java.util.hashmapをインポートします。 java.util.mapをインポートします。 / ** * *ページネーションクエリ補助クラス * @author li xiaogui 2016年11月9日13:55:37 */パブリッククラスページ{ //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- pageCurrentPage;//How many pages are private int PageBegin; // Position Private int numcount; //プライベートint pageTotalの総数; //プライベート文字列順序= ""; //ソートページに表示されるプライベート文字列順方向指向の総数= ""; public page(){} public page(int pagesize、int pagecurrentpage){super(); this.pagesize = pagesize; this.pagecurrentPage = pageCurrentPage; } public(map <string、string> map){if(map.get( "pagenum")!= null){this.setpagecurrentpage(this.pagecurrentpage = integer.parseint( "pagenum")); if(map.get( "numperpage")!= null){this.setPagesize(integer.parseint( "numperpage")); } if(map.get( "OrderDirection")!= null){this.setOrderDirection(map.get( "OrderDirection")); }} public int getPageCurrentPage(){return pagecurrentpage; } public void setPageCurrentPage(int pageCurrentPage){this.pageCurrentPage = pageCurrentPage; } public int getNumcount(){return numcount; } public void setnumcount(int numcount){this.numcount = numcount; } public int getPageTotal(){return(numcount%pagesize> 0)?(numcount/pagesize+1):( numcount/pagesize); } public void setPagetotal(int pagetotal){this.pagetotal = pagetotal; } public int getPagesize(){return pagesize; } public void setPagesize(int pagesize){this.pagesize = pagesize; } public int getPageBegin(){return Pagesize*(pagecurrentPage-1); } public void setPageBegin(int pagebegin){this.pagebegin = pagebegin; } public string getOrderField(){return orderfield; } public void setorderfield(String Orderfield){this.orderfield = Orderfield; } public string getOrderDirection(){return orderDirection; } public void setOrderDirection(String OrderDirection){this.OrderDirection = OrderDirection; } public static Page getPage(int pagesize、int pagecurrentpage){return new Page(Pagesize、PageCurrentPage); } public static Page getPage(マップマップ){new Pageを返す(マップ); }}コントローラーでメソッドを呼び出します
パブリック文字列リスト(httpservletrequest request){long a = system.currenttimemillis(); hashmap <string、object> map = getRequestMap.getMap(request); // [メソッド]自分でメソッドをカプセル化するには、page = page.getPage(map); // page map.put( "page"、page); //ページオブジェクトをパラメーターセットに入れます(このマップはmybatisなどが使用されます。 map.put(map.get( "Orderfield")+""、map.get( "OrderDirection")); list <employee> list = employeservice.getListPage(Map); request.setattribute( "emlist"、list); request.setattribute( "page"、page); request.setattribute( "Map"、Map); //ページに関連する属性を取得するpage.getnumcount(); //ページの総数page.getPageTotal(); //ページの総数long b = system.currenttimemillis(); system.out.println( "--------------時間消費:"+(ba)+"ms"); "Basic/Employee_list"を返します。 }最後に、春にプラグインを構成します
<bean id = "pageinterector"> < /bean> <! - spring and mybatisは完全に統合されており、mybatis構成マッピングファイルは必要ありません - > <bean id = "sqlsessionfactory"> <プロパティ名= "datasource" ref = "datasource" />> <! value = "classPath:com/dnkx/mapping/*。xml"> </property> <プロパティ名= "プラグイン"> <ref bean = "pageinterector"/> </property> </bean>
わかりました、それは終わりです、この記事は参照のみです!偉大な神のアドバイスを楽しみにしています