MyBatis Interceptor Paging

Source: Internet
Author: User

 PackageCom.test.interceptor;Importjava.sql.Connection;ImportJava.sql.ResultSet;Importjava.sql.SQLException;Importjava.util.List;ImportJava.util.Map;Importjava.util.Properties;ImportOrg.apache.ibatis.executor.Executor;ImportOrg.apache.ibatis.executor.parameter.ParameterHandler;ImportOrg.apache.ibatis.executor.statement.RoutingStatementHandler;ImportOrg.apache.ibatis.executor.statement.StatementHandler;Importorg.apache.ibatis.mapping.BoundSql;Importorg.apache.ibatis.mapping.MappedStatement;Importorg.apache.ibatis.mapping.ParameterMapping;ImportOrg.apache.ibatis.plugin.Interceptor;Importorg.apache.ibatis.plugin.Intercepts;Importorg.apache.ibatis.plugin.Invocation;ImportOrg.apache.ibatis.plugin.Plugin;Importorg.apache.ibatis.plugin.Signature;ImportOrg.apache.ibatis.reflection.MetaObject;ImportOrg.apache.ibatis.reflection.SystemMetaObject;ImportOrg.apache.ibatis.scripting.defaults.DefaultParameterHandler;ImportOrg.apache.ibatis.session.ResultHandler;Importorg.apache.ibatis.session.RowBounds;Importcom.mysql.jdbc.PreparedStatement;Importcom.test.util.Page; @Intercepts ({@Signature (type= Statementhandler.class, method = "Prepare", args = {Connection.class}), @Signature (method= "Query", type = Executor.class, args ={mappedstatement.class, Object.class, Rowbounds.class, Resulthandler.class }) }) Public classStatementhandleinterceptorImplementsInterceptor { Public Static FinalString mysql = "MySQL"; protectedThreadlocal<page> pagethreadlocal =NewThreadlocal<page>();  PublicObject Intercept (invocation invocation)throwsThrowable {if(Invocation.gettarget ()instanceofStatementhandler) {Page<?> page =Pagethreadlocal.get (); if(page==NULL){                returninvocation.proceed (); } Routingstatementhandler Statementhandler=(Routingstatementhandler) invocation. Gettarget (); Statementhandler Delegate=Reflectutil.getfieldvalue (Statementhandler,"Delegate"); Boundsql Boundsql=Delegate.getboundsql (); Connection Connection= (Connection) invocation.getargs () [0]; if(Page.gettotalpage () >-1) {System.out.println ("Total Pages:" +page.gettotalpage ()); }Else{Object obj=Boundsql.getparameterobject (); MetaObject Metastatementhandler=Systemmetaobject.forobject (Statementhandler); Mappedstatement mappedstatement= (mappedstatement) metastatementhandler.getvalue ("Delegate.mappedstatement");            Querytotalrecord (page, obj, mappedstatement, connection); } String SQL=Boundsql.getsql (); String Pagesql=Buildpagesql (Page,sql); System.out.println ("When paging, generate Pagesql:" +pagesql); Reflectutil.setfieldvalue (Object) Boundsql,"SQL", Pagesql); returninvocation.proceed (); }Else{Page<?> page = Findpageobject (Invocation.getargs () [1]); if(page==NULL) {System.out.println ("No page Parameter object, not paged query"); returninvocation.proceed (); }Else{System.out.println ("Page object detected! Using paged query");            } pagethreadlocal.set (page); Try{                returninvocation.proceed (); //can setpage Results                /*Object resultobj = Invocation.proceed ();                if (resultobj instanceof list) {Page.setresults ((List) resultobj); } return resultobj;*/                            }finally{pagethreadlocal.remove (); }        }             }         PrivateString buildpagesql (Page page,string sql) {//calculates the position of the first record, which is recorded in MySQL starting at 0.         intoffset = (Page.getpageno ()-1) *page.getpagesize (); return NewStringBuilder (SQL). Append ("Limit"). Append (offset). Append (","). Append (Page.getpagesize ()). ToString (); }            /*** Determine if paging interception is required *@paramObject *@return     */    PrivatePage<?>Findpageobject (Object object) {if(ObjectinstanceofPage<?>){            return(page<?>) object; }Else if(ObjectinstanceofMap) {             for(Object o: (map<?,? >object). Values ()) {if(OinstanceofPage<?>){                    return(page<?>) O; }            }        }        return NULL; }    /*** Query Total number of records *@paramPage *@paramobj *@paramMappedstatement *@paramConnection *@throwsSQLException*/    Private voidQuerytotalrecord (page<?>page, Object obj, mappedstatement mappedstatement, Connection Connection)throwsSQLException {boundsql boundsql=mappedstatement.getboundsql (page); String SQL=Boundsql.getsql (); String Countsql= This. Buildcountsql (SQL); System.out.println ("When paging, generate Countsql:" +countsql); List<ParameterMapping> parametermappings =boundsql.getparametermappings (); Boundsql Countboundsql=NewBoundsql (Mappedstatement.getconfiguration (), countsql,parametermappings,obj); Parameterhandler Parameterhandler=NewDefaultparameterhandler (mappedstatement, obj, countboundsql); PreparedStatement pstmt=NULL; ResultSet RS=NULL; Try{pstmt=(PreparedStatement) connection.preparestatement (countsql);            Parameterhandler.setparameters (PSTMT); RS=Pstmt.executequery (); if(Rs.next ()) {LongTotalrecord = Rs.getlong (1);            Page.settotalrecord (Totalrecord); }            }finally{            if(rs!=NULL) {rs.close (); }            if(pstmt!=NULL) {pstmt.close (); }        }            }    /*** Construct query total record Count SQL *@paramSQL *@return     */    Privatestring Buildcountsql (String sql) {intindex = Sql.tolowercase (). IndexOf ("from"); return"SELECT COUNT (*)" +sql.substring (index); }     PublicObject Plugin (object target) {returnPlugin.wrap (Target, This); }     Public voidSetProperties (Properties properties) {}}

Call

Results:

MyBatis Interceptor Paging

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.