Just start the project, need to use to mybatis pagination, the internet saw a lot of plug-ins, in fact, the basic principle of implementation is basically the same, but most of them only give the code, the comments are not complete, so refer to a lot of articles (each article steal a bit of code, the number of their own, To imitate themselves to write a suitable for their own project paging Plug-ins, not to say more directly on the code, compared to most of the article, the annotation is complete
The most important interceptor.
Package com.dnkx.interceptor;
Import java.sql.*;
Import Java.util.HashMap;
Import java.util.Properties;
Import Org.apache.ibatis.executor.resultset.ResultSetHandler;
Import Org.apache.ibatis.executor.statement.StatementHandler;
Import ORG.APACHE.IBATIS.MAPPING.BOUNDSQL;
Import org.apache.ibatis.mapping.MappedStatement;
Import Org.apache.ibatis.plugin.Interceptor;
Import org.apache.ibatis.plugin.Intercepts;
Import org.apache.ibatis.plugin.Invocation;
Import Org.apache.ibatis.plugin.Plugin;
Import Org.apache.ibatis.plugin.Signature;
Import Org.apache.ibatis.reflection.MetaObject;
Import Org.apache.ibatis.reflection.SystemMetaObject;
Import Com.dnkx.pojo.Page;
/** * * Paging interceptor, used to intercept operations that require paging queries, and then page-handle them. * Using interceptors to implement the principle of mybatis paging: * To use JDBC to operate the database, you must have a corresponding statement object, MyBatis A statement object that contains the SQL statement before executing the SQL statement. and the corresponding SQL statement * is generated before statement, so we can start the SQL statement used to generate the statement before it generates statement. In MyBatis, the statement statement is generated by the Routingstatementhandler object's * Prepare method. So one idea of using interceptor to realize mybatis paging isIntercepts the prepare method of the Statementhandler interface, then changes the SQL statement to the corresponding paging query SQL statement in the Interceptor method, and then calls the prepare method of the * Statementhandler object.
That is, call Invocation.proceed (). * For paging, one of the operations we need to do in the interceptor is to count the number of records that meet the current conditions, which are changed to the corresponding statistical statements after obtaining the original SQL statement and then use the MyBatis encapsulated parameters and set *
The function of the set parameter replaces the parameters in the SQL statement, then executes the SQL statement that queries the number of records to count the total number of records. * Explain some of the classes that might be used in the plugin: * Metaobject:mybatis provides a class * Boundsql based on the object that returns the property value: In this you can get the SQL to execute and the parameters to execute SQL * mappedstate
ment: This gets the value of the ID that the currently executing SQL statement configures in the XML file * rowbounds: It is mybatis memory paging.
* Parameterhandler: Is mybatis used to replace the value that appears in SQL. * * @author Lee 10:59:04 November 9, 2016 * * * * * * * @Intercepts ({@Signature type=statementhandler.class,method= "prepare", Args={con Nection.class}), @Signature (type = Resultsethandler.class, method = "Handleresultsets", args = {statement.class})}) PU
Blic class Pageinterceptor implements interceptor{/block paging keyword private static final String select_id= "page"; Plug-in to run the code, it will replace the original method, to rewrite the most important intercept @Override public Object intercept (invocation invocation) throws Throwable {if (i Nvocation.getTarget () instanceof Statementhandler) {//Here we have a setting. If the Query method contains page pagination other methods are ignored//so it is necessary to get the method name Statementhandler Statementhan
Dler= (Statementhandler) invocation.gettarget ();
MetaObject Metaobject=systemmetaobject.forobject (Statementhandler);
Mappedstatement mappedstatement= (mappedstatement) metaobject.getvalue ("Delegate.mappedstatement");
String Selectid=mappedstatement.getid (); String methorname=selectid.substring (Selectid.lastindexof (".")
+1). toLowerCase (); Then judge if you have page to get SQL if (Methorname.contains (select_id)) {Boundsql boundsql= (boundsql) Metaobject.getvalue ("
Delegate.boundsql ");
The paging parameter is a property String Sql=boundsql.getsql () as a Parameter object parameterobject.
SYSTEM.OUT.PRINTLN ("Acquired sql:" +sql);
Hashmap<string, object> map= (hashmap<string, object>) (Boundsql.getparameterobject ());
Page page= (page) (Boundsql.getparameterobject ());
Page page= (page) map.get ("page");
Rewrite SQL String countsql=concatcountsql (SQL);
String Pagesql=concatpagesql (sql,page); SYSTEM.OUT.PRINTLN ("rewritten CoUNT sql: "+countsql";
SYSTEM.OUT.PRINTLN ("Overridden Select sql:" +pagesql);
Connection Connection = (Connection) invocation.getargs () [0];
PreparedStatement countstmt = null;
ResultSet rs = null;
int totalcount = 0;
try {countstmt = connection.preparestatement (Countsql);
rs = Countstmt.executequery ();
if (Rs.next ()) {totalcount = Rs.getint (1);
The catch (SQLException e) {System.out.println ("Ignore This exception" +e);
Finally {try {rs.close ();
Countstmt.close ();
catch (SQLException e) {System.out.println ("Ignore this exception" + E);
} metaobject.setvalue ("Delegate.boundSql.sql", pagesql);
Bind Count Page.setnumcount (totalcount);
} return Invocation.proceed (); }//Intercept type Statementhandler, overriding plugin method @Override public Object Plugin (object target) {if (Target instanceof Statementha
Ndler) {return Plugin.wrap (target, this);
}else {return target; @Override public void SetProperties (properties properties) {}//Transform 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 ("SELECT count (*) from (" +sql+ ") tmp");
return sb.tostring ();
public string Concatpagesql (string Sql,page Page) {stringbuffer sb=new stringbuffer ();
Sb.append (SQL);
Sb.append ("Limit"). Append (Page.getpagebegin ()). Append (","). Append (Page.getpagesize ());
return sb.tostring ();
The Paging Object page class [Java] View plain copy package Com.dnkx.pojo;
Import Java.util.HashMap;
Import Java.util.Map; /** * * Paging Query Auxiliary class * @author Lee Small turn November 9, 2016 13:55:37 */public class Page {//----------pagination-----------Private int page size;//display bars per page private inT pagecurrentpage;//first page private int pagebegin;//start position private int numcount;//total number private int pagetotal;//Total Bar number private St
Ring OrderField = "";//Control the sort page to display the private String orderdirection = "";
Public page () {} public page (int pageSize, int pagecurrentpage) {super ();
This.pagesize = pageSize;
This.pagecurrentpage = Pagecurrentpage; Public Page (map<string, string> Map) {if (Map.get ("Pagenum")!=null) {This.setpagecurrentpage ( This.pagecurrentpage = Integer.parseint (Map.get ("Pagenum"))//number of pages to query}else{this.setpagecurrentpage (1);//Set initial value} if (Map.get ("Numperpage")!=null) {this.setpagesize (Integer.parseint (Map.get ("Numperpage"));//per page display number}else{this.setpagesize (5);//Set initial value} if (
Map.get ("OrderField")!=null) {This.setorderfield (Map.get ("OrderField"));
} 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;
The public void Setnumcount (int numcount) {this.numcount = Numcount; public int getpagetotal () {return (numcount%pagesize>0)? (
NUMCOUNT/PAGESIZE+1):(numcount/pagesize);
The public void setpagetotal (int pagetotal) {this.pagetotal = Pagetotal;
public int getpagesize () {return pageSize;
The public void setpagesize (int pageSize) {this.pagesize = pageSize;
public int Getpagebegin () {return pagesize* (pageCurrentPage-1);
The 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 (map map) {return new page (map); }
}
Controller Inside Call Way
Public String list (HttpServletRequest request) {
long a=system.currenttimemillis ();
Hashmap<string,object> Map=getrequestmap.getmap (Request), and/or its encapsulated method, take the parameters of the request
Page page= Page.getpage ( map);//Initialize page
map.put ("page", page);//Put the page object into the parameter collection (this map is mybatis to use, contains query criteria, sorting, paging, etc.)
/Control sort page display
Map.put (Map.get ("OrderField") + "", Map.get ("orderdirection"));
List<employee> list=employeeservice.getlistpage (map);
Request.setattribute ("emlist", list);
Request.setattribute ("page", page);
Request.setattribute ("map", map);
Take page-related attributes Page.getnumcount ()
//Total number of
page.getpagetotal ()//Total pages
long B=system.currenttimemillis () ;
System.out.println ("---------Time Consuming:" + (B-A) + "MS");
return "Basic/employee_list";
}
Finally, spring inside the configuration plug-in
<bean id= "Pageinterector" class= "Com.dnkx.interceptor.PageInterceptor" ></bean>
<!-- Spring and MyBatis are perfectly integrated without the need for MyBatis configuration mapping files--> <bean id= "Sqlsessionfactory"
Org.mybatis.spring.SqlSessionFactoryBean ">
<property name=" DataSource "ref=" DataSource "/>
<! --Automatically scan mapping.xml files--> <property name= "mapperlocations" value= "Classpath:com/dnkx/mapping/*.xml"
> </property>
<property name= "Plugins" >
<ref bean= "Pageinterector"/>
</property >
</bean>
OK, here's the end, this article is for reference only! Also look forward to the great God's advice