1. Package Paging Page class
Package Com.framework.common.page.impl;
Import java.io.Serializable;
Import Com.framework.common.page.IPage; /** * * */Public abstract class BasePage implements IPage, Serializable {/** * * * private static fin
Al long serialversionuid = -3623448612757790359l;
public static int default_page_size = 20;
private int pageSize = Default_page_size;
private int currentresult;
private int totalpage;
private int currentpage = 1;
private int totalcount =-1;
public basepage (int currentpage, int pageSize, int totalcount) {this.currentpage = CurrentPage;
This.pagesize = pageSize;
This.totalcount = TotalCount;
public int Gettotalcount () {return this.totalcount;
The public void Settotalcount (int totalcount) {if (TotalCount < 0) {this.totalcount = 0;
Return
} this.totalcount = TotalCount;
Public BasePage () {} public int getfirstresult () {return (this.currentpage-1) * this.pagesize; The public void setpagesize (int pageSize) {if (PageSize < 0) {this.pagesize = default_page_size;
Return
} 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;
} return this.totalpage;
public int getpagesize () {return this.pagesize;
The 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;
return this.currentpage + 1; public int Getcurrentresult () {This.currentresult = (gEtpageno ()-1) * getpagesize ());
if (This.currentresult < 0) {This.currentresult = 0;
return this.currentresult;
public int Getprepage () {if (Isfirstpage ()) {return this.currentpage;
return this.currentpage-1;
}
}
Package Com.framework.common.page.impl;
Import java.util.List;
/** * * */public
class Page extends BasePage {
/**
* */
private static final Long serialversionuid = -970177928709377315l;
public static threadlocal<page> ThreadLocal = new threadlocal<page> ();
Private list<?> data;
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, Totalc Ount);
This.data = data;
}
Public list<?> GetData () {return
data;
}
public void SetData (list<?> data) {
This.data = Data
}
}
2. Package Paging Plugin
Package com.framework.common.page.plugin;
Import java.sql.Connection;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;
Import java.sql.SQLException;
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;
Import Org.apache.ibatis.executor.statement.BaseStatementHandler;
Import Org.apache.ibatis.executor.statement.RoutingStatementHandler;
Import ORG.APACHE.IBATIS.MAPPING.BOUNDSQL;
Import org.apache.ibatis.mapping.MappedStatement;
Import org.apache.ibatis.mapping.ParameterMapping;
Import Org.apache.ibatis.mapping.ParameterMode;
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.reflection.MetaObject; Import Org.apache.ibatis.reflection.property.PrOpertytokenizer;
Import Org.apache.ibatis.scripting.xmltags.ForEachSqlNode;
Import 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.Statement Handler.class, method = ' prepare ', args = {Connection.class}}) public class Pageplugin implements interceptor {PRI
vate String dialect = "";
Private String Pagesqlid = ""; @Override public Object intercept (invocation invocation) throws Throwable {if (Invocation.gettarget () instanceof Ro Utingstatementhandler) {Basestatementhandler delegate = (Basestatementhandler) reflectutil. Getvaluebyfie
Ldname ((Routingstatementhandler) Invocation.gettarget (), "delegate"); Mappedstatement mappedstatement = (mappedstatement) reflectutil. Getvaluebyfieldname (Delegate, "Mappedstatement");
Page page = 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 = Boundsql.getparameterobject ();
String sql = Boundsql.getsql ();
String countsqlid = Mappedstatement.getid (). ReplaceAll (Pagesqlid, "Count");
Mappedstatement countmappedstatement = null; if (Mappedstatement.getconfiguration (). Hasstatement (Countsqlid)) {countmappedstatement = Mappedstatement.getcon
Figuration (). Getmappedstatement (Countsqlid);
} String countsql = null;
if (countmappedstatement!= null) {Countsql = Countmappedstatement.getboundsql (parameterobject). GETSQL (); else {countsql = "select COUNT (1) from (" + SQL + ") T_count";
int totalcount = 0;
PreparedStatement countstmt = null;
ResultSet ResultSet = null;
try {Connection Connection = (Connection) invocation.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);
The catch (Exception e) {throw e;
Finally {try {if (ResultSet!= null) {resultset.close (); } finally {if (countstmt!= null) {Countstmt.cloSE ();
}} page.settotalcount (TotalCount);
Reflectutil.setvaluebyfieldname (Boundsql, "SQL", Generatepagesql (Sql,page));
} return Invocation.proceed (); /** * to SQL parameters (?) Set value, reference Org.apache.ibatis.executor.parameter.DefaultParameterHandler * @param PS * @param mappedstatement * @para M Boundsql * @param parameterobject * @throws SQLException/private void Setparameters (PreparedStatement Ps,mappedstatement Mappedstatement,boundsql boundsql,object parameterobject) throws SQLException {Errorcontext.insta
NCE (). Activity ("Setting parameters"). Object (Mappedstatement.getparametermap (). GetId ());
list<parametermapping> parametermappings = Boundsql.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 value;
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 (prop
Ertyname); 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.getnam
E (). length ());
} else {value = MetaObject = null null:metaObject.getValue (propertyname);
} Typehandler Typehandler = Parametermapping.gettypehandler (); if (Typehandler = = null) {throw new Executorexception ("There is no Typehandler found for parameter" + Prope
Rtyname + "of statement" + Mappedstatement.getid ());
Typehandler.setparameter (PS, i + 1, value, Parametermapping.getjdbctype ()); /** * Based on database dialect, generates a specific paging SQL * @param SQL * @param page * @return/Priva Te string Generatepagesql (String Sql,page Page) {if (Page!=null && Stringutils.isnotblank (dialect)) {St
Ringbuffer 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 *" (select Tmp_tb.*,rownum row_id from ());
Pagesql.append (SQL);
Pagesql.append (") as TMP_TB WHERE rownum <=");
Pagesql.append (Page.getcurrentresult () +page.getpagesize ());
Pagesql.append (") WHERE row_id >");
Pagesql.append (Page.getcurrentresult ());
return pagesql.tostring ();
}else{return SQL;
@Override public Object Plugin (object target) {return plugin.wrap (target); @Override public void SetProperties (properties properties) {try {if stringutils.isempty (This.dialect =
Properties. GetProperty ("dialect")) {throw new Propertyexception ("Dialect property isn't found!"); } if (Stringutils.isempty = This.pagesqlid = properties. GetProperty ("Pagesqlid")) {throw new Propertyexception (" Pagesqlid property isn't found! ");}
catch (Propertyexception e) {e.printstacktrace ();
}
}
}
3.MyBatis Config file: mybatis-config.xml
<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE configuration Public "-//mybatis.org//dtd SQL Map Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd ">
<configuration>
<plugins>
<plugin interceptor=" Com.framework.common.page.plugin.PagePlugin ">
<property name=" dialect "value=" MySQL "/>
< Property Name= "Pagesqlid" value= "Bypage"/>
</plugin>
</plugins>
</configuration >
4. Paging Interceptor
Package com.framework.common.page.interceptor;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import Org.apache.commons.lang3.math.NumberUtils;
Import Org.springframework.web.servlet.ModelAndView;
Import Org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
Import Com.framework.common.page.impl.Page; /** * * */public class Pageinterceptor extends Handlerinterceptoradapter {@Override public void Posthandle (Http ServletRequest request, HttpServletResponse response, Object handler, Modelandview Modelandview) throws Exceptio
n {super.posthandle (request, response, Handler, Modelandview);
Page page = Page.threadLocal.get ();
if (page!= null) {Request.setattribute ("page", page);
} Page.threadLocal.remove (); @Override public boolean prehandle (HttpServletRequest request, httpservletresponse response, Object handler) thr oWS Exception {String pageSize = request.getparameter ("pageSize ");
String PageNo = Request.getparameter ("PageNo");
Page page = new page ();
if (Numberutils.isnumber (pageSize)) {page.setpagesize (Numberutils.toint (pageSize));
} if (Numberutils.isnumber (PageNo)) {Page.setpageno (Numberutils.toint (PageNo));
} Page.threadLocal.set (Page);
return true;
}
}
5.Spring Configuration
<!--===================================================================-Load Property file-================== =================================================--> <context:property-placeholder location= "classpath:
Application.properties "/> <bean id= sqlsessionfactory" class= "Org.mybatis.spring.SqlSessionFactoryBean" > <property name= "DataSource" ref= "DataSource/> <property name=" configlocation "value=" classpath: Mybatis-config.xml "/> <property name=" mapperlocations "> <list> <value>classpath:/com/fra mework/mapper/**/*mapper.xml</value> </list> </property> </bean> <!--================== =================================================-by scanning the mode, scanning the directory all the DAO, according to the corresponding mapper.xml for it to generate proxy class-================= ==================================================--> <bean id= "Mapperscannerconfigurer" class= " Org.mybatis.spring.mapper.MapperScannerConfigurer "> <property name=" basePackage "value=" Com.framework.dao "/> <property name=" Processpropertyplaceholders "value=" true "/>
Rty name= "Sqlsessionfactorybeanname" value= "Sqlsessionfactory"/> </bean>
6.SpringMVC Configuration Interceptor
<!--paging Interceptor-->
<bean id= "Pageinterceptor" class= " Com.framework.common.page.interceptor.PageInterceptor "></bean>
<!--configuration Interceptor-->
<bean class= "Org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" >
< Property name= "Interceptors" >
<list>
<ref bean= "Pageinterceptor"/>
</list>
</property>
</bean>