欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Mybatis全面分页插件

程序员文章站 2024-03-13 20:07:39
根据下面分页的思想,很容易实现mybitas的多租户设计。  使用mybatis提供的拦截器。对分页的sql语句通过封装处理,处理成不同的分页sql。 ...

根据下面分页的思想,很容易实现mybitas的多租户设计。 

使用mybatis提供的拦截器。对分页的sql语句通过封装处理,处理成不同的分页sql。 

本例已经实现了对mysql和oracle的分页功能。注意下面的引用包,不要引用错了。 

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 org.apache.ibatis.executor.parameter.parameterhandler;
import org.apache.ibatis.executor.statement.routingstatementhandler;
import org.apache.ibatis.executor.statement.statementhandler;
import org.apache.ibatis.mapping.boundsql;
import org.apache.ibatis.mapping.mappedstatement;
import org.apache.ibatis.mapping.parametermapping;
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.scripting.defaults.defaultparameterhandler;

import com.yidao.utils.page;
import com.yidao.utils.reflecthelper;

/** 
 * 
 * 分页拦截器,用于拦截需要进行分页查询的操作,然后对其进行分页处理。 
 * 利用拦截器实现mybatis分页的原理: 
 * 要利用jdbc对数据库进行操作就必须要有一个对应的statement对象,mybatis在执行sql语句前就会产生一个包含sql语句的statement对象,而且对应的sql语句 
 * 是在statement之前产生的,所以我们就可以在它生成statement之前对用来生成statement的sql语句下手。在mybatis中statement语句是通过routingstatementhandler对象的 
 * prepare方法生成的。所以利用拦截器实现mybatis分页的一个思路就是拦截statementhandler接口的prepare方法,然后在拦截器方法中把sql语句改成对应的分页查询sql语句,之后再调用 
 * statementhandler对象的prepare方法,即调用invocation.proceed()。 
 * 对于分页而言,在拦截器里面我们还需要做的一个操作就是统计满足当前条件的记录一共有多少,这是通过获取到了原始的sql语句后,把它改为对应的统计语句再利用mybatis封装好的参数和设 
 * 置参数的功能把sql语句中的参数进行替换,之后再执行查询记录数的sql语句进行总记录数的统计。 
 * 
 */ 
@intercepts({@signature(type=statementhandler.class,method="prepare",args={connection.class})})
public class pageinterceptor implements interceptor {
 private string dialect = ""; //数据库方言 
 private string pagesqlid = ""; //mapper.xml中需要拦截的id(正则匹配) 
  
 public object intercept(invocation invocation) throws throwable {
  //对于statementhandler其实只有两个实现类,一个是routingstatementhandler,另一个是抽象类basestatementhandler, 
  //basestatementhandler有三个子类,分别是simplestatementhandler,preparedstatementhandler和callablestatementhandler, 
  //simplestatementhandler是用于处理statement的,preparedstatementhandler是处理preparedstatement的,而callablestatementhandler是 
  //处理callablestatement的。mybatis在进行sql语句处理的时候都是建立的routingstatementhandler,而在routingstatementhandler里面拥有一个 
  //statementhandler类型的delegate属性,routingstatementhandler会依据statement的不同建立对应的basestatementhandler,即simplestatementhandler、 
  //preparedstatementhandler或callablestatementhandler,在routingstatementhandler里面所有statementhandler接口方法的实现都是调用的delegate对应的方法。 
  //我们在pageinterceptor类上已经用@signature标记了该interceptor只拦截statementhandler接口的prepare方法,又因为mybatis只有在建立routingstatementhandler的时候 
  //是通过interceptor的plugin方法进行包裹的,所以我们这里拦截到的目标对象肯定是routingstatementhandler对象。
  if(invocation.gettarget() instanceof routingstatementhandler){ 
   routingstatementhandler statementhandler = (routingstatementhandler)invocation.gettarget(); 
   statementhandler delegate = (statementhandler) reflecthelper.getfieldvalue(statementhandler, "delegate"); 
   boundsql boundsql = delegate.getboundsql();
   object obj = boundsql.getparameterobject();
   if (obj instanceof page<?>) { 
    page<?> page = (page<?>) obj; 
    //通过反射获取delegate父类basestatementhandler的mappedstatement属性 
    mappedstatement mappedstatement = (mappedstatement)reflecthelper.getfieldvalue(delegate, "mappedstatement"); 
    //拦截到的prepare方法参数是一个connection对象 
    connection connection = (connection)invocation.getargs()[0]; 
    //获取当前要执行的sql语句,也就是我们直接在mapper映射语句中写的sql语句 
    string sql = boundsql.getsql(); 
    //给当前的page参数对象设置总记录数 
    this.settotalrecord(page, 
      mappedstatement, connection); 
    //获取分页sql语句 
    string pagesql = this.getpagesql(page, sql); 
    //利用反射设置当前boundsql对应的sql属性为我们建立好的分页sql语句 
    reflecthelper.setfieldvalue(boundsql, "sql", pagesql); 
   } 
  } 
  return invocation.proceed(); 
 }
 
 /** 
  * 给当前的参数对象page设置总记录数 
  * 
  * @param page mapper映射语句对应的参数对象 
  * @param mappedstatement mapper映射语句 
  * @param connection 当前的数据库连接 
  */ 
 private void settotalrecord(page<?> page, 
   mappedstatement mappedstatement, connection connection) { 
  //获取对应的boundsql,这个boundsql其实跟我们利用statementhandler获取到的boundsql是同一个对象。 
  //delegate里面的boundsql也是通过mappedstatement.getboundsql(paramobj)方法获取到的。 
  boundsql boundsql = mappedstatement.getboundsql(page); 
  //获取到我们自己写在mapper映射语句中对应的sql语句 
  string sql = boundsql.getsql(); 
  //通过查询sql语句获取到对应的计算总记录数的sql语句 
  string countsql = this.getcountsql(sql); 
  //通过boundsql获取对应的参数映射 
  list<parametermapping> parametermappings = boundsql.getparametermappings(); 
  //利用configuration、查询记录数的sql语句countsql、参数映射关系parametermappings和参数对象page建立查询记录数对应的boundsql对象。 
  boundsql countboundsql = new boundsql(mappedstatement.getconfiguration(), countsql, parametermappings, page); 
  //通过mappedstatement、参数对象page和boundsql对象countboundsql建立一个用于设定参数的parameterhandler对象 
  parameterhandler parameterhandler = new defaultparameterhandler(mappedstatement, page, countboundsql); 
  //通过connection建立一个countsql对应的preparedstatement对象。 
  preparedstatement pstmt = null; 
  resultset rs = null; 
  try { 
   pstmt = connection.preparestatement(countsql); 
   //通过parameterhandler给preparedstatement对象设置参数 
   parameterhandler.setparameters(pstmt); 
   //之后就是执行获取总记录数的sql语句和获取结果了。 
   rs = pstmt.executequery(); 
   if (rs.next()) { 
    int totalrecord = rs.getint(1); 
    //给当前的参数page对象设置总记录数 
    page.settotalrecord(totalrecord); 
   } 
  } catch (sqlexception e) { 
   e.printstacktrace(); 
  } finally { 
   try { 
    if (rs != null) 
     rs.close(); 
    if (pstmt != null) 
     pstmt.close(); 
   } catch (sqlexception e) { 
    e.printstacktrace(); 
   } 
  } 
 } 
 
 /** 
  * 根据原sql语句获取对应的查询总记录数的sql语句 
  * @param sql 
  * @return 
  */ 
 private string getcountsql(string sql) { 
  int index = sql.indexof("from"); 
  return "select count(*) " + sql.substring(index); 
 } 
 
 /** 
  * 根据page对象获取对应的分页查询sql语句,这里只做了两种数据库类型,mysql和oracle 
  * 其它的数据库都 没有进行分页 
  * 
  * @param page 分页对象 
  * @param sql 原sql语句 
  * @return 
  */ 
 private string getpagesql(page<?> page, string sql) { 
  stringbuffer sqlbuffer = new stringbuffer(sql); 
  if ("mysql".equalsignorecase(dialect)) { 
   return getmysqlpagesql(page, sqlbuffer); 
  } else if ("oracle".equalsignorecase(dialect)) { 
   return getoraclepagesql(page, sqlbuffer); 
  } 
  return sqlbuffer.tostring(); 
 } 
 
 /** 
 * 获取mysql数据库的分页查询语句 
 * @param page 分页对象 
 * @param sqlbuffer 包含原sql语句的stringbuffer对象 
 * @return mysql数据库分页语句 
 */ 
 private string getmysqlpagesql(page<?> page, stringbuffer sqlbuffer) { 
  //计算第一条记录的位置,mysql中记录的位置是从0开始的。 
// system.out.println("page:"+page.getpage()+"-------"+page.getrows());
  int offset = (page.getpage() - 1) * page.getrows(); 
  sqlbuffer.append(" limit ").append(offset).append(",").append(page.getrows()); 
  return sqlbuffer.tostring(); 
 } 
 
 /** 
 * 获取oracle数据库的分页查询语句 
 * @param page 分页对象 
 * @param sqlbuffer 包含原sql语句的stringbuffer对象 
 * @return oracle数据库的分页查询语句 
 */ 
 private string getoraclepagesql(page<?> page, stringbuffer sqlbuffer) { 
  //计算第一条记录的位置,oracle分页是通过rownum进行的,而rownum是从1开始的 
  int offset = (page.getpage() - 1) * page.getrows() + 1; 
  sqlbuffer.insert(0, "select u.*, rownum r from (").append(") u where rownum < ").append(offset + page.getrows()); 
  sqlbuffer.insert(0, "select * from (").append(") where r >= ").append(offset); 
  //上面的sql语句拼接之后大概是这个样子: 
  //select * from (select u.*, rownum r from (select * from t_user) u where rownum < 31) where r >= 16 
  return sqlbuffer.tostring(); 
 } 
 
  
 /** 
  * 拦截器对应的封装原始对象的方法 
  */  
 public object plugin(object arg0) { 
  // todo auto-generated method stub 
  if (arg0 instanceof statementhandler) { 
   return plugin.wrap(arg0, this); 
  } else { 
   return arg0; 
  } 
 } 
 
 /** 
  * 设置注册拦截器时设定的属性 
  */ 
 public void setproperties(properties p) {
  
 }

 public string getdialect() {
 return dialect;
 }

 public void setdialect(string dialect) {
 this.dialect = dialect;
 }

 public string getpagesqlid() {
 return pagesqlid;
 }

 public void setpagesqlid(string pagesqlid) {
 this.pagesqlid = pagesqlid;
 }
 
} 

xml配置: 

<!-- mybatis 接口编程配置 -->
 <bean class="org.mybatis.spring.mapper.mapperscannerconfigurer">
  <!-- basepackage指定要扫描的包,在此包之下的映射器都会被搜索到,可指定多个包,包与包之间用逗号或分号分隔-->
  <property name="basepackage" value="com.yidao.mybatis.dao" />
  <property name="sqlsessionfactorybeanname" value="sqlsessionfactory" />
 </bean>
 
 <!-- mybatis 分页拦截器-->
 <bean id="paginationinterceptor" class="com.mybatis.interceptor.pageinterceptor">
  <property name="dialect" value="mysql"/> 
  <!-- 拦截mapper.xml文件中,id包含query字符的语句 --> 
  <property name="pagesqlid" value=".*query$"/>
 </bean> 

page类

 package com.yidao.utils;


/**自己看看,需要什么字段加什么字段吧*/
public class page {
 
 private integer rows;
 
 private integer page = 1;
 
 private integer totalrecord;

 public integer getrows() {
 return rows;
 }

 public void setrows(integer rows) {
 this.rows = rows;
 }

 public integer getpage() {
 return page;
 }

 public void setpage(integer page) {
 this.page = page;
 }

 public integer gettotalrecord() {
 return totalrecord;
 }

 public void settotalrecord(integer totalrecord) {
 this.totalrecord = totalrecord;
 }
 
}


reflecthelper类

package com.yidao.utils;

import java.lang.reflect.field;

import org.apache.commons.lang3.reflect.fieldutils;

public class reflecthelper {
 
 public static object getfieldvalue(object obj , string fieldname ){
 
 if(obj == null){
 return null ;
 }
 
 field targetfield = gettargetfield(obj.getclass(), fieldname);
 
 try {
 return fieldutils.readfield(targetfield, obj, true ) ;
 } catch (illegalaccessexception e) {
 e.printstacktrace();
 } 
 return null ;
 }
 
 public static field gettargetfield(class<?> targetclass, string fieldname) {
 field field = null;

 try {
 if (targetclass == null) {
 return field;
 }

 if (object.class.equals(targetclass)) {
 return field;
 }

 field = fieldutils.getdeclaredfield(targetclass, fieldname, true);
 if (field == null) {
 field = gettargetfield(targetclass.getsuperclass(), fieldname);
 }
 } catch (exception e) {
 }

 return field;
 }
 
 public static void setfieldvalue(object obj , string fieldname , object value ){
 if(null == obj){return;}
 field targetfield = gettargetfield(obj.getclass(), fieldname); 
 try {
 fieldutils.writefield(targetfield, obj, value) ;
 } catch (illegalaccessexception e) {
 e.printstacktrace();
 } 
 } 
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。