Implementing physical paging with MyBatis

Source: Internet
Author: User

MyBatis has a weak paging function, which is a memory-based paging ( find all records and then take the result by offset and limit), such paging is basically useless in the case of large data volumes. This article is based on plugins, by interceptingStatementhandlerrewriteSQLstatement that implements the physical paging of the database. This article is adapted to a MyBatis version is 3.2.7 . The specific implementation is as follows:

Paginationinterceptor class:

Package Org.reacher.interceptor.pagination;import Java.sql.connection;import Java.sql.preparedstatement;import Java.sql.resultset;import Java.sql.sqlexception;import Java.util.properties;import Org.apache.commons.logging.Log ; Import Org.apache.commons.logging.logfactory;import Org.apache.ibatis.executor.parameter.ParameterHandler; 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 Org.apache.ibatis.scripting.defaults.defaultparameterhandler;import Org.apache.ibatis.session.rowbounds;import Org.reacher.interceptor.pagination.dialect.dialect;import Org.reacher.interceptor.paginaTion.dialect.dialectfactory;import org.reacher.interceptor.pagination.model.pagebounds;/** * @author Reacher * * Paginationinterceptor */@Intercepts ({@Signature (type = Statementhandler.class, method = "Prepare", args = { Connection.class})}) public class Paginationinterceptor implements interceptor {private static final log log = Logfactory. GetLog (paginationinterceptor.class);p rivate class<?> clazz = null; @Overridepublic Object intercept (invocation Invocation) throws Throwable {if (null = = This.clazz) {log.error ("not found have been initialized database dialect!"); return Invocation.proceed ();} Final dialect dialect = dialectfactory.getdialect (This.clazz), if (null = = dialect) {log.error (This.clazz.getName () + " Initialized failed! "); return Invocation.proceed ();} Final Statementhandler Statementhandler = (statementhandler) invocation.gettarget (); final MetaObject Metastatementhandler = Systemmetaobject.forobject (Statementhandler); final rowbounds rowbounds = (RowBounds) Metastatementhandler.GetValue ("Delegate.rowbounds"); PageBounds pagebounds = null;if (rowbounds instanceof pagebounds) {pagebounds = (pagebounds) rowBounds;} if (null = = PageBounds | | 0 >= pagebounds.getsize () | | 0 >= pagebounds.getnumber ()) {return invocation.proceed ();} Final Mappedstatement mappedstatement = (mappedstatement) metastatementhandler.getvalue ("Delegate.mappedstatement") ; final Boundsql boundsql = Statementhandler.getboundsql (); final Object parameterobject = Boundsql.getparameterobject () ; final Connection Connection = (Connection) invocation.getargs () [0];p Agebounds.setcount (This.getcount ( Mappedstatement, connection, Parameterobject, dialect)); Metastatementhandler.setvalue ("Delegate.boundSql.sql",        Dialect.getlimitsql (Boundsql.getsql (), Pagebounds.getsize () * (Pagebounds.getnumber ()-1), pagebounds.getsize ());        Metastatementhandler.setvalue ("Delegate.rowBounds.offset", Rowbounds.no_row_offset); Metastatementhandler.setvalue ("Delegate.rowBounds.limit", rowbounds.no_row_limit); retUrn Invocation.proceed ();} @Overridepublic Object Plugin (object target) {return Plugin.wrap (target, this);} @Overridepublic void SetProperties (Properties properties) {String dialectname = Properties.getproperty ("dialect"); NULL = = Dialectname) {log.error ("property dialectname isn ' t set!"); return;} try {this.clazz = Class.forName (Dialectname),} catch (ClassNotFoundException e) {log.error (e);}} private int GetCount (final mappedstatement mappedstatement, final Connection Connection, final Object parameterobject, fi Nal dialect dialect) {final Boundsql boundsql = Mappedstatement.getboundsql (parameterobject); final String countsql = dial Ect.getcountsql (Boundsql.getsql ()); PreparedStatement preparedstatement = null; ResultSet ResultSet = Null;int count = 0;try {PreparedStatement = Connection.preparestatement (countsql); final Parameterhandler handler = new Defaultparameterhandler (mappedstatement, Parameterobject, Boundsql); Handler.setparameters (preparedstatement); resultSet = Preparedstatement.executEquery (); if (Resultset.next ()) {count = Resultset.getint (1);}} catch (Exception e) {log.error (e);} finally {if (PreparedStatement! = null) {try {preparedstatement.close ();} catch (Sqlex Ception e) {log.error (e);}}} return count;}}
dialectInterface:

Package org.reacher.interceptor.pagination.dialect;/** * @author Reacher * */public interface dialect {/** * Check whether the database supports paging * /public Abstract Boolean supportslimit ();/** * Get the SQL statement that gets the total number of data bars */public string getcountsql (String sql);/** * Get paged SQL statement */ Public abstract string Getlimitsql (String sql, long offset, long limit);}
Dialectfactory Factory class:
Package Org.reacher.interceptor.pagination.dialect;import Java.lang.reflect.constructor;import Java.util.HashMap; Import java.util.map;/** * @author Reacher * */public Final class Dialectfactory {private static map<string, Dialect> ; dialects = new hashmap<string, dialect> ();p ublic static dialect getdialect (class<?> clazz) throws Exception { Dialect dialect = Dialects.get (Clazz.getsimplename ()), if (dialect = = null) {dialect = newinstance (clazz); if (null! = Diale CT) {dialects.put (Clazz.getsimplename (), dialect);}} return dialect;} private static dialect newinstance (class<?> clazz) throws Exception {if (null = = Clazz) {return null;} constructor<?> Constructor = Clazz.getconstructor (); constructor.setaccessible (true); Object object = Constructor.newinstance ();D Ialect dialect = null;if (Object instanceof dialect) {dialect = (dialect) object;} return dialect;}}
PageBounds class:

Package Org.reacher.interceptor.pagination.model;import org.apache.ibatis.session.rowbounds;/** * @author Reacher * * /public class PageBounds extends Rowbounds {private int size;//page size private int number;//current page private int count;//data total number of bars Priv ate int total;//Total pages Public pagebounds () {this.number = 1;this.size = 10;} Public pagebounds (int pageSize) {this.number = 1;this.size = pageSize;} public int GetSize () {return size;} public void setSize (int size) {this.size = size;} public int GetNumber () {return number;} public void Setnumber (int number) {this.number = number;} public int GetCount () {return count;} public void SetCount (int count) {This.count = count;} public int gettotal () {this.total = this.count/this.size + (this.count% this.size > 0? 1:0); return this.total;} public void Settotal (int. total) {this.total = total;}}
The implementation of the MySQL database paging is as follows:

Mysqldialect class:

Package Org.reacher.interceptor.pagination.dialect.database;import org.reacher.interceptor.pagination.dialect.dialect;/** * @author Reacher * */public class Mysqldialect implements Dialect {@Overridepublic Boolean supportslimit () {return true;} @Overridepublic string Getcountsql (String sql) {return "Select COUNT (*) from (" + Sql.replaceall (";", "") + ") temp";} @Overridepublic string Getlimitsql (String sql, long offset, long limit) {StringBuffer StringBuffer = new StringBuffer (SQL. ReplaceAll (";", "")); Stringbuffer.append ("Limit"). Append (offset). Append (","). Append (limit); return Stringbuffer.tostring ();}}
The Mybatis-configuration.xml configuration is as follows:

<plugins><span style= "White-space:pre" ></span><plugininterceptor= " Org.reacher.interceptor.pagination.PaginationInterceptor "><property name=" dialect "value=" Org.reacher.interceptor.pagination.dialect.database.MySQLDialect "/></plugin></plugins>


Implementing physical paging with MyBatis

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.