当前位置: 移动技术网 > IT编程>开发语言>Java > 自己动手写的mybatis分页插件(极其简单好用)

自己动手写的mybatis分页插件(极其简单好用)

2019年07月22日  | 移动技术网IT编程  | 我要评论

tcl网络电视,中融信托圭顿财富,隆安教育信息网

刚开始项目,需要用到mybatis分页,网上看了很多插件,其实实现原理基本都大同小异,但是大部分都只给了代码,注释不全,所以参考了很多篇文章(每篇文章偷一点代码,评出来自己的,半抄袭),才自己模仿着写出了一个适合自己项目的分页插件,话不多说,直接上代码,相比大部分文章,注释算很完整了

最重要的拦截器

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; 
/** 
* 
* 分页拦截器,用于拦截需要进行分页查询的操作,然后对其进行分页处理。 
* 利用拦截器实现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语句进行总记录数的统计。 
* 
* 解释一下插件中可能要用到的几个类: 
* metaobject:mybatis提供的一个基于返回获取属性值的对象的类 
* boundsql : 在这个里面可以获取都要执行的sql和执行sql要用到的参数 
* mappedstatement : 这个可以得到当前执行的sql语句在xml文件中配置的id的值 
* rowbounds : 是mybatis内存分页要用到的。 
* parameterhandler : 是mybatis中用来替换sql中?出现的值的. 
* 
* @author 李小拐 2016年11月9日 10:59:04 
*/ 
@intercepts({ 
@signature(type=statementhandler.class,method="prepare",args={connection.class}), 
@signature(type = resultsethandler.class, method = "handleresultsets", args = {statement.class}) 
}) 
public class pageinterceptor implements interceptor{ 
//拦截分页关键字 
private static final string select_id="page"; 
//插件运行的代码,它将代替原有的方法,要重写最重要的intercept了 
@override 
public object intercept(invocation invocation) throws throwable { 
if (invocation.gettarget() instanceof statementhandler) { 
//这里我们有一个设定 如果查询方法含有page 就进行分页 其他方法无视 
//所以就要获取方法名 
statementhandler statementhandler=(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(); 
//然后判断下 如果含有page 就获取sql 
if(methorname.contains(select_id)){ 
boundsql boundsql=(boundsql)metaobject.getvalue("delegate.boundsql"); 
//分页参数作为参数对象parameterobject的一个属性 
string sql=boundsql.getsql(); 
system.out.println("获取到的sql:"+sql); 
hashmap<string, object> map=(hashmap<string, object>)(boundsql.getparameterobject()); 
//page page=(page)(boundsql.getparameterobject()); 
page page=(page)map.get("page"); 
// 重写sql 
string countsql=concatcountsql(sql); 
string pagesql=concatpagesql(sql,page); 
// system.out.println("重写的 count sql :"+countsql); 
system.out.println("重写的 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); 
} 
} 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); 
//绑定count 
page.setnumcount(totalcount); 
} 
} 
return invocation.proceed(); 
} 
// 拦截类型statementhandler,重写plugin方法 
@override 
public object plugin(object target) { 
if (target instanceof statementhandler) { 
return plugin.wrap(target, this); 
}else { 
return target; 
} 
} 
@override 
public void setproperties(properties properties) { 
} 
//改造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(); 
} 
} 
分页对象page类
[java] view plain copy
package com.dnkx.pojo; 
import java.util.hashmap; 
import java.util.map; 
/** 
* 
* 分页查询辅助类 
* @author 李小拐 2016年11月9日 13:55:37 
*/ 
public class page { 
//----------分页----------- 
private int pagesize;//每页显示条数 
private int pagecurrentpage;//第几页 
private int pagebegin;//开始位置 
private int numcount;//总条数 
private int pagetotal;//总条数 
private string orderfield = "";//控制排序页面显示的 
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")));//要查询的页数 
}else{ 
this.setpagecurrentpage(1);//设置初始值 
} 
if(map.get("numperpage")!=null){ 
this.setpagesize(integer.parseint(map.get("numperpage")));//每页显示条数 
}else{ 
this.setpagesize(5);//设置初始值 
} 
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; 
} 
public void setnumcount(int numcount) { 
this.numcount = numcount; 
} 
public int getpagetotal() { 
return (numcount%pagesize>0)?(numcount/pagesize+1):(numcount/pagesize); 
} 
public void setpagetotal(int pagetotal) { 
this.pagetotal = pagetotal; 
} 
public int getpagesize() { 
return pagesize; 
} 
public void setpagesize(int pagesize) { 
this.pagesize = pagesize; 
} 
public int getpagebegin() { 
return pagesize*(pagecurrentpage-1); 
} 
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里面调用方式

public string list(httpservletrequest request) { 
long a=system.currenttimemillis(); 
hashmap<string,object> map=getrequestmap.getmap(request);//自己封装的方法,取request的参数 
page page= page.getpage(map);//初始化page 
map.put("page", page);//把page对象放入参数集合(这个map是mybatis要用到的,包含查询条件,排序,分页等) 
//控制排序页面显示的 
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); 
//取page相关属性 
page.getnumcount();//总条数 
page.getpagetotal();//总页数 
long b=system.currenttimemillis(); 
system.out.println("---------耗时:"+(b-a)+"ms"); 
return "basic/employee_list"; 
}

最后,spring里面配置插件

<bean id="pageinterector" class="com.dnkx.interceptor.pageinterceptor"></bean> 
<!-- spring和mybatis完美整合,不需要mybatis的配置映射文件 --> 
<bean id="sqlsessionfactory" class="org.mybatis.spring.sqlsessionfactorybean"> 
<property name="datasource" ref="datasource" /> 
<!-- 自动扫描mapping.xml文件 --> 
<property name="mapperlocations" value="classpath:com/dnkx/mapping/*.xml"></property> 
<property name="plugins"> 
<ref bean="pageinterector"/> 
</property> 
</bean>

好了,到此结束,本文仅供参考!也期待大神提意见

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网