[Java] [MyBatis] Physical Paging implementation __ Database zone

Source: Internet
Author: User

[Java] [MyBatis] Physical paging implementation

MYBATIS3.0 has been out for some time, in fact, I really like such a persistent framework, because it is simple and practical, low learning costs. The Mybatis3.0 is similar in overall structure to ibatis2.x, and the improved features are as follows:

1. Parsing XML introduced XPath, unlike Ibatis2.x's amateur

2. Dynamic SQL with OGNL parsing

3. Add annotation configuration sql, feel nothing particularly big use, I prefer XML, code and configuration separation, this is the original intention of Ibatis

4. Enhanced caching of this piece of functionality. Mybatis3.0 the cache module into a finer, divided into "persistent implementation (Prepetual)" and "Resource recycling policy Implementation (eviction)", better to the caching function of their own combination and expansion

5. Finally joined the plugin function, just like struts, so that it can be a good extension of the internal executor,,statementhandler ... etc. internal object function.

MyBatis paging functionality is based on memory paging (a record that finds all records to remove offsets, and if the JDBC drive supports absolute positioning or rs.next () to the specified offset ), such paging implementations are essentially useless, especially in the case of large amounts of data. However, we can extend the paging function of MyBatis and realize physical paging through the plugin function. The following are specific practices:

1. Write the paging plug-in class:

/** * Copyright: Huaxin Software * Project Name: ACWS Frame class * Creator: WANGDF * Date Created: 2014-4-2 * File Description: ACWS Framework Paging Interface class/package FRAMEWORK.CORE.INTERCEP

Tor
Import java.sql.Connection;
Import Java.util.Map;

Import java.util.Properties;
Import Org.apache.commons.collections.MapUtils;
Import Org.apache.ibatis.executor.statement.StatementHandler;
Import ORG.APACHE.IBATIS.MAPPING.BOUNDSQL;
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.factory.DefaultObjectFactory;
Import Org.apache.ibatis.reflection.factory.ObjectFactory;
Import Org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory;
Import Org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
Import org.apache.ibatis.session.Configuration;

Import Org.apache.ibatis.session.RowBounds; Import FRAMEWORK.COre.util.DBUtil; /** * ACWS Framework Pagination Interface class * @author WANGDF */@Intercepts ({@Signature (type = Statementhandler.class, method = "Prepare", AR GS = {Connection.class})}) public class Paginationinterceptor implements interceptor {private static final OBJECTF
    Actory default_object_factory = new Defaultobjectfactory ();

	private static final Objectwrapperfactory default_object_wrapper_factory = new Defaultobjectwrapperfactory (); @Override public Object intercept (invocation invocation) throws Throwable {Statementhandler Statementhandler = (statem
		Enthandler) Invocation.gettarget (); MetaObject Metastatementhandler = Metaobject.forobject (Statementhandler, Default_object_factory, DEFAULT_

		Object_wrapper_factory);
		Rowbounds rowbounds = (rowbounds) metastatementhandler.getvalue ("Delegate.rowbounds");
		if (rowbounds = null | | rowbounds = = rowbounds.default) {return invocation.proceed (); //Detach Agent object chain (since the target class may be intercepted by multiple interceptors to form multiple proxies, the original target can be separated by the following two cycles)Class) while (Metastatementhandler.hasgetter ("H")) {object = Metastatementhandler.getvalue ("h");
        Metastatementhandler = Metaobject.forobject (object, Default_object_factory, default_object_wrapper_factory); The target class of the last proxy object, while (Metastatementhandler.hasgetter ("target")) {object =
            Metastatementhandler.getvalue ("target");
        Metastatementhandler = Metaobject.forobject (object, Default_object_factory, default_object_wrapper_factory);
        
    	} boundsql Boundsql = (boundsql) metastatementhandler.getvalue ("Delegate.boundsql");
		String sql = Boundsql.getsql ();

    	StringBuffer sbsql = new StringBuffer ();
		Rewrite sql Configuration Configuration = (Configuration) metastatementhandler.getvalue ("Delegate.configuration");
        Dbutil dbutil = new Dbutil (configuration); if (Dbutil.ismysql ()) {sbsql.append (SQL). Append ("LIMIT"). Append (Rowbounds.getoffset ()). Append (",").Append (Rowbounds.getlimit ());
            
            Metastatementhandler.setvalue ("Delegate.boundSql.sql", sbsql.tostring ()); With physical paging, you do not need mybatis memory paging, so reset the following two parameters Metastatementhandler.setvalue ("Delegate.rowBounds.offset", Rowbounds.
            No_row_offset);
		Metastatementhandler.setvalue ("Delegate.rowBounds.limit", rowbounds.no_row_limit);
			else if (dbutil.isoracle ()) {sbsql.append ("select *");
			Sbsql.append ("From" (select RowNum RN, nopagesql.*);
			Sbsql.append ("From ("). append (SQL). Append (") Nopagesql");
			Sbsql.append ("WHERE rownum <="). Append (Rowbounds.getlimit () +rowbounds.getoffset ()). Append (")");
	        Sbsql.append ("WHERE RN >="). Append (Rowbounds.getoffset ());
	        
	        Metastatementhandler.setvalue ("Delegate.boundSql.sql", sbsql.tostring ()); With physical paging, you do not need mybatis memory paging, so reset the following two parameters Metastatementhandler.setvalue ("Delegate.rowBounds.offset", Rowbounds.no_
	        Row_offset); MetastAtementhandler.setvalue ("Delegate.rowBounds.limit", rowbounds.no_row_limit);
	else {}//to give execution to the next interceptor return Invocation.proceed ();
        @Override public Object Plugin (object target) {//when the target class is Statementhandler type, wrap the target class, or return the target itself directly, reducing the number of times the target is being represented
        if (target instanceof Statementhandler) {return Plugin.wrap (target, this);
        else {return target; @Override public void SetProperties (properties properties) {//TODO auto-generated method stub}}

2. Configure Read class

/** * Copyright: Huaxin Software * Project name: ACWS Framework class * Creator: WANGDF * Date Created: 2014-4-2 * Document Description: ACWS Framework Database related tools/package framework.core.util;
Import Org.apache.commons.lang.StringUtils;
Import org.apache.ibatis.session.Configuration;
Import Org.slf4j.Logger;

Import Org.slf4j.LoggerFactory; /** * ACWS Framework Database related Tools class * @author WANGDF/public class Dbutil {private static final String Dbtype_mysql = "MYSQL";/support  Type: mysql,oracle private static final String dbtype_oracle = "Oracle";//Supported type: mysql,oracle private static Logger Logger
	= Loggerfactory.getlogger (Dbutil.class);
	
	Private Configuration Configuration = null;
	Private String DbType = "";
	
	Private String Defaultdateformat = ""; Public Dbutil (Configuration Configuration) {if (Configuration = = null) {Logger.error ("System startup failure: MyBatis Configuration object is Empty.
			"); throw new IllegalArgumentException (System boot failed: MyBatis Configuration object is empty.
		");
		} this.configuration = Configuration;
	This.dbtype = This.configuration.getVariables (). GetProperty ("DbType");    if (Stringutils.isblank (DbType)) {logger.error ("database type is not configured.)
	    ");
	    else {logger.info ("Database type:" +dbtype);
	    } This.defaultdateformat = This.configuration.getVariables (). GetProperty ("Defaultdateformat");
	    	if (Stringutils.isblank (This.defaultdateformat)) {this.defaultdateformat= "YYYY-MM-DD"; Logger.info (the database date default format string is not specified.)
	    System defaults to: Yyyy-mm-dd ");
	    else {logger.info ("Database date default format string:" +this.defaultdateformat); }/** * Determine if ORACLE database * @return * @author WANGDF/public boolean isoracle () {return Dbtype_oracle.equa
	LS (this.dbtype); /** * To determine whether the MYSQL database * @return * @author WANGDF/public boolean ismysql () {return dbtype_mysql.equals t
	His.dbtype);
	/** * Get the database type * @return * @author WANGDF/public String Getdbtype () {return this.dbtype; /** * Gets the default date format * @return * @author WANGDF/public String Getdefaultdateformat () {return THIS.DEFAULTDA
	Teformat;
 }

}


3, in the MyBatis global configuration file Settings

<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE configuration Public "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd" >
<configuration>
	
	<properties>
	    <property name= "DbType" value= "MySQL"/><!-- Database type: MySQL, Oracle-->
	    <property name= "Defaultdateformat" value= "Yyyy-mm-dd"/>
	</properties >

	<settings>
		<setting name= "cacheenabled" value= "true"/> <setting
		" Lazyloadingenabled "value=" true "/> <setting name=" multipleresultsetsenabled "value=
		" true "/>
		<setting name= "Usecolumnlabel" value= "true"/> <setting name=
		"Defaultexecutortype" value= "REUSE"/>
		<setting name= "defaultstatementtimeout" value= "25000"/>
	</settings>
	
	<plugins>
		<plugin interceptor= "Framework.core.interceptor.PaginationInterceptor" ></plugin>
	</ Plugins>
</configuration>



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.