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

MyBatis Plus插件机制与执行流程原理分析详解

程序员文章站 2022-09-16 21:40:19
mybatis plus插件mybatis plus提供了分页插件paginationinterceptor、执行分析插件sqlexplaininterceptor、性能分析插件performance...

mybatis plus插件

mybatis plus提供了分页插件paginationinterceptor、执行分析插件sqlexplaininterceptor、性能分析插件performanceinterceptor以及乐观锁插件optimisticlockerinterceptor。

mybatis 通过插件 (interceptor) 可以做到拦截四大对象相关方法的执行 ,根据需求完成相关数据的动态改变。

四大对象是:

  • executor
  • statementhandler
  • parameterhandler
  • resultsethandler

四大对象的每个对象在创建时,都会执行interceptorchain.pluginall(),会经过每个插件对象的 plugin()方法,目的是为当前的四大对象创建代理。代理对象就可以拦截到四大对象相关方法的执行,因为要执行四大对象的方法需要经过代理 。

① xml下插件的配置

如下所示:

<bean id="sqlsessionfactorybean" class="com.baomidou.mybatisplus.spring.mybatissqlsessionfactorybean">
<!-- 数据源 -->
<property name="datasource" ref="datasource">
</property>
<property name="configlocation" value="classpath:mybatis-config.xml">
</property>
<!-- 别名处理 --><property name="typealiasespackage" value="com.jane.mp.beans">
</property>
<!-- 注入全局mp策略配置 --><property name="globalconfig" ref="globalconfiguration">
</property>
<!-- 插件注册 --><property name="plugins"><list><!-- 注册分页插件 -->
<bean class="com.baomidou.mybatisplus.plugins.paginationinterceptor">
</bean>
<!-- 注册执行分析插件 --><bean class="com.baomidou.mybatisplus.plugins.sqlexplaininterceptor">
<property name="stopproceed" value="true"></property></bean>
<!-- 注册性能分析插件 -->
<bean class="com.baomidou.mybatisplus.plugins.performanceinterceptor"><property name="format" value="true">
</property>
<!-- <property name="maxtime" value="5"></property> --></bean>
<!-- 注册乐观锁插件 -->
<bean class="com.baomidou.mybatisplus.plugins.optimisticlockerinterceptor"></bean>
</list></property></bean>

② springboot下注册插件

这里以分页插件为例:

@bean public paginationinterceptor paginationinterceptor() 
{  
paginationinterceptor paginationinterceptor = new paginationinterceptor();  
// 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求 默认false  
// paginationinterceptor.setoverflow(false); 
// 设置最大单页限制数量,默认 500 条,-1 不受限制  
// paginationinterceptor.setlimit(500); 
// 开启 count 的 join 优化,只针对部分 left join  
paginationinterceptor.setcountsqlparser(new jsqlparsercountoptimize(true)); 
return paginationinterceptor; 
}

③ sqlexplaininterceptor

sql执行分析拦截器,全类名是com.baomidou.mybatisplus.plugins.sqlexplaininterceptor,只支持 mysql5.6.3以上版本。

该插件的作用是分析 delete update语句 ,防止小白或者恶意进行delete update全表操作,不建议在生产环境中使用会造成性能下降,

在插件的底层通过sql语句分析命令 explain 分析当前的 sql语句,根据结果集中的 extra列来断定当前是否全表操作。

④ 性能分析插件

性能分析拦截器,全类名是com.baomidou.mybatisplus.plugins.performanceinterceptor,用于输出每条 sql 语句及其执行时间。sql性能执行分析 ,开发环境使用 超过指定时间,停止运行。

⑤ 乐观锁插件

全类名是com.baomidou.mybatisplus.plugins.optimisticlockerinterceptor。如果想实现如下需求 : 当要更新一条记录的时候,希望这条记录没有被别人更新,就可以使用该插件进行判断。

乐观锁的实现原理(@version 用于注解实体字段,必须要有) :

  • 取出记录时,获取当前 version
  • 更新时,带上这个version
  • 执行更新时,set version = yourversion+1 where version = yourversion
  • 如果 version不对,就更新失败

【2】获取sqlsessionfactorybean

如下图所示,在系统启动时会初始化定义的bean。defaultlistablebeanfactory.preinstantiatesingletons方法中会从beandefinitionnames中获取bean name然后依次创建。

这里可以看到rootbeandefinition是com.baomidou.mybatisplus.spring.mybatissqlsessionfactorybean。

MyBatis Plus插件机制与执行流程原理分析详解

① 获取bean的过程中bean属性

如下所示,在getbean过程中可以看到bean的属性:

MyBatis Plus插件机制与执行流程原理分析详解

② createbean

第一次获取bean的时候会走到abstractautowirecapablebeanfactory.createbean进行bean的创建。

 /** 创建一个bean实例,为bean实例设置属性值,调用post-processors-bean后置处理器 */@overrideprotected object createbean(string beanname, rootbeandefinition mbd, object[] args) 
 throws beancreationexception 
 {//...暂时忽略其他代码 
 try {// 这里会首先触发beanpostprocessors ,如果这里能获取到bean则直接返回,不再走docreatebean 
 object bean = resolvebeforeinstantiation(beanname, mbdtouse); 
 if (bean != null)
 { 
 return bean; 
 } }//...暂时忽略其他代码

在abstractautowirecapablebeanfactory.resolvebeforeinstantiation中就会分别执行bean后置处理器的前置和后置方法。

protected object resolvebeforeinstantiation(string beanname, rootbeandefinition mbd) 
{ object bean = null; 
if (!boolean.false.equals(mbd.beforeinstantiationresolved))
{ 
// make sure bean class is actually resolved at this point. 
if (!mbd.issynthetic() && hasinstantiationawarebeanpostprocessors())
{  
class<?> targettype = determinetargettype(beanname, mbd);  
if (targettype != null) {  
bean = applybeanpostprocessorsbeforeinstantiation(targettype, beanname);  
if (bean != null)
{   
bean = applybeanpostprocessorsafterinitialization(bean, beanname);  
}  
} 
} 
mbd.beforeinstantiationresolved = (bean != null); 
} 
return bean;
}

执行后置处理器的前置方法如下所示:

MyBatis Plus插件机制与执行流程原理分析详解

③ docreatebean

abstractautowirecapablebeanfactory.docreatebean是创建bean的核心方法,这会为bean属性赋值并会触发bean后置处理器、initializingbean以及自定init方法等。

protected object docreatebean(final string beanname, final rootbeandefinition mbd, final object[] args) throws beancreationexception 
{
// instantiate the bean.--实例化beanbeanwrapper instancewrapper = null;if (mbd.issingleton()) { instancewrapper = this.factorybeaninstancecache.remove(beanname);}if (instancewrapper == null) 
{//获取bean的包装对象-这里很重要 instancewrapper = createbeaninstance(beanname, mbd, args);}final object bean = (instancewrapper != null ? instancewrapper.getwrappedinstance() : null);class<?> beantype = (instancewrapper != null ? instancewrapper.getwrappedclass() : null);mbd.resolvedtargettype = beantype;
// allow post-processors to modify the merged bean definition.synchronized (mbd.postprocessinglock) 
{ if (!mbd.postprocessed)
 { try {//调用mergedbeandefinitionpostprocessors的postprocessmergedbeandefinition方法  applymergedbeandefinitionpostprocessors(mbd, beantype, beanname); 
} catch (throwable ex) 
{ 
 throw new beancreationexception(mbd.getresourcedescription(), beanname,   "post-processing of merged bean definition failed", ex); 
} mbd.postprocessed = true; }}//...//这里暂时忽略其他代码
// initialize the bean instance.--初始化bean实例object exposedobject = bean;try {//如下方法很重要 populatebean(beanname, mbd, instancewrapper); if (exposedobject != null) 
{ 
 exposedobject = initializebean(beanname, exposedobject, mbd); 
}}//...

④ populatebean

顾名思义,为bean实例属性赋值。

abstractautowirecapablebeanfactory.populatebean

protected void populatebean(string beanname, rootbeandefinition mbd, beanwrapper bw) {//获取属性值列表propertyvalues pvs = mbd.getpropertyvalues();
//...该种符号表示暂时忽略其他代码
//在为bean属性赋值前,给instantiationawarebeanpostprocessors 机会修改bean的状态//应用场景如支持字段注入boolean continuewithpropertypopulation = true;
//循环调用instantiationawarebeanpostprocessors 的postprocessafterinstantiation方法if (!mbd.issynthetic() && hasinstantiationawarebeanpostprocessors()) { for (beanpostprocessor bp : getbeanpostprocessors()) { if (bp instanceof instantiationawarebeanpostprocessor) {  instantiationawarebeanpostprocessor ibp = (instantiationawarebeanpostprocessor) bp;  if (!ibp.postprocessafterinstantiation(bw.getwrappedinstance(), beanname)) {  continuewithpropertypopulation = false;  break;  } } }}
if (!continuewithpropertypopulation) { return;}//解析autowire注解字段,进行主动注入if (mbd.getresolvedautowiremode() == rootbeandefinition.autowire_by_name || mbd.getresolvedautowiremode() == rootbeandefinition.autowire_by_type) { mutablepropertyvalues newpvs = new mutablepropertyvalues(pvs);
 // add property values based on autowire by name if applicable. if (mbd.getresolvedautowiremode() == rootbeandefinition.autowire_by_name) { autowirebyname(beanname, mbd, bw, newpvs); }
 // add property values based on autowire by type if applicable. if (mbd.getresolvedautowiremode() == rootbeandefinition.autowire_by_type) { autowirebytype(beanname, mbd, bw, newpvs); }
 pvs = newpvs;}boolean hasinstawarebpps = hasinstantiationawarebeanpostprocessors();boolean needsdepcheck = (mbd.getdependencycheck() != rootbeandefinition.dependency_check_none);//循环调用instantiationawarebeanpostprocessors 的postprocesspropertyvalues方法if (hasinstawarebpps || needsdepcheck) { propertydescriptor[] filteredpds = filterpropertydescriptorsfordependencycheck(bw, mbd.allowcaching); if (hasinstawarebpps) { for (beanpostprocessor bp : getbeanpostprocessors()) {  if (bp instanceof instantiationawarebeanpostprocessor) {  instantiationawarebeanpostprocessor ibp = (instantiationawarebeanpostprocessor) bp;  pvs = ibp.postprocesspropertyvalues(pvs, filteredpds, bw.getwrappedinstance(), beanname);  if (pvs == null) {   return;  }  } } } if (needsdepcheck) { checkdependencies(beanname, mbd, filteredpds, pvs); }}//在这里为属性赋值,会进行类型转换,这里注意关键词deep copy//如果是引用类型且bean没有存在,则会进行bean的创建过程applypropertyvalues(beanname, mbd, bw, pvs);}

如下图所示在创建sqlsessionfactorybean过程中会创建其属性globalconfiguration对象:

MyBatis Plus插件机制与执行流程原理分析详解


如下图所示在创建sqlsessionfactorybean过程中(从左侧的方法顺序就可以看出来)会创建其属性paginationinterceptor对象:

MyBatis Plus插件机制与执行流程原理分析详解


如下图所示在创建sqlsessionfactorybean过程中(从左侧的方法顺序就可以看出来)会创建其属性sqlexplaininterceptor对象:

MyBatis Plus插件机制与执行流程原理分析详解


如下图所示在创建sqlsessionfactorybean过程中(从左侧的方法顺序就可以看出来)会创建其属性performanceinterceptor对象:

MyBatis Plus插件机制与执行流程原理分析详解


如下图所示在创建sqlsessionfactorybean过程中(从左侧的方法顺序就可以看出来)会创建其属性optimisticlockerinterceptor对象:

MyBatis Plus插件机制与执行流程原理分析详解


⑤ initializebean

abstractautowirecapablebeanfactory.initializebean源码如下:

protected object initializebean(final string beanname, final object bean, rootbeandefinition mbd)
{ 
if (system.getsecuritymanager() != null) 
{ 
accesscontroller.doprivileged(new privilegedaction<object>() 
{ 
@override  public object run() 
{  
invokeawaremethods(beanname, bean);  
return null; 
} 
}, getaccesscontrolcontext()); } else { //调用意识/通知方法 invokeawaremethods(beanname, bean); 
}
 object wrappedbean = bean; 
 if (mbd == null || !mbd.issynthetic())
 { //调用bean后置处理器的前置方法 
 wrappedbean = applybeanpostprocessorsbeforeinitialization(wrappedbean, beanname); 
 } //调用初始化方法 
 try { 
 invokeinitmethods(beanname, wrappedbean, mbd); 
 } catch (throwable ex) 
 { 
 throw new beancreationexception(  
 (mbd != null ? mbd.getresourcedescription() : null),  
 beanname, "invocation of init method failed", ex); 
 }

abstractautowirecapablebeanfactory.invokeinitmethods方法源码如下:

protected void invokeinitmethods(string beanname, final object bean, rootbeandefinition mbd) 
throws throwable {
 boolean isinitializingbean = (bean instanceof initializingbean); 
 if (isinitializingbean && (mbd == null || !mbd.isexternallymanagedinitmethod("afterpropertiesset"))) 
 { 
 if (logger.isdebugenabled()) 
 {  
 logger.debug("invoking afterpropertiesset() on bean with name '" + beanname + "'"); 
 } 
 //调用initializingbean.afterpropertiesset 
 if (system.getsecuritymanager() != null)
 {  
 try {  
 accesscontroller.doprivileged(new privilegedexceptionaction<object>()
 {  
 @override   public object run() throws exception 
 {   
 ((initializingbean) bean).afterpropertiesset();   
 return null;  
 }  }, getaccesscontrolcontext()); 
 }  
 catch (privilegedactionexception pae) 
 {  
 throw pae.getexception(); 
 } } else {  ((initializingbean) bean).afterpropertiesset(); 
 } }//调用自定义初始化方法 if (mbd != null)
 { 
 string initmethodname = mbd.getinitmethodname(); 
 if (initmethodname != null && !(isinitializingbean && "afterpropertiesset".equals(initmethodname)) &&  
 !mbd.isexternallymanagedinitmethod(initmethodname))
 {  
 invokecustominitmethod(beanname, bean, mbd); 
 } 
 }}

如下图所示,mybatissqlsessionfactorybean同样实现了initializingbean接口。那么我们就需要注意其afterpropertiesset方法了。

MyBatis Plus插件机制与执行流程原理分析详解

⑥ mybatissqlsessionfactorybean.afterpropertiesset

如下所示,代码很简短只是创建了sqlsessionfactory。

@overridepublic void afterpropertiesset() throws exception
{ 
notnull(datasource, "property 'datasource' is required"); //sqlsessionfactorybuilder在populatebean的applypropertyvalues过程中已经存在! 
notnull(sqlsessionfactorybuilder, "property 'sqlsessionfactorybuilder' is required"); 
state((configuration == null && configlocation == null) || !(configuration != null && configlocation != null),  
"property 'configuration' and 'configlocation' can not specified with together");
 this.sqlsessionfactory = buildsqlsessionfactory();
 }

进入afterpropertiesset()方法前mybatissqlsessionfactorybean如下所示:

MyBatis Plus插件机制与执行流程原理分析详解

我们看一下sqlsessionfactory,这是一段很长的过程:

protected sqlsessionfactory buildsqlsessionfactory() throws exception
{ 
configuration configuration; // todo 加载自定义 mybatisxmlconfigbuilder 
mybatisxmlconfigbuilder xmlconfigbuilder = null; 
if (this.configuration != null) 
{  
configuration = this.configuration;  
if (configuration.getvariables() == null) 
{  
 configuration.setvariables(this.configurationproperties);  
 } else if (this.configurationproperties != null)
 {  
 configuration.getvariables().putall(this.configurationproperties);  
 } 
 } else if (this.configlocation != null) { //通常如果配置了configlocation会从这里创建mybatisxmlconfigbuilder, //其构造方法又创建了mybatisconfiguration 
 xmlconfigbuilder = new mybatisxmlconfigbuilder(this.configlocation.getinputstream(), null, this.configurationproperties);  
 configuration = xmlconfigbuilder.getconfiguration(); } else {  
 if (logger.isdebugenabled()) {   
 logger.debug("property 'configuration' or 'configlocation' not specified, using default mybatis configuration");  
 }  
 // todo 使用自定义配置  
 configuration = new mybatisconfiguration();  
 if (this.configurationproperties != null)
 {  
 configuration.setvariables(this.configurationproperties);  
 } }
 if (this.objectfactory != null)
 {  
 configuration.setobjectfactory(this.objectfactory); 
 }
 if (this.objectwrapperfactory != null)
 {  
 configuration.setobjectwrapperfactory(this.objectwrapperfactory); 
 }
 if (this.vfs != null) {  configuration.setvfsimpl(this.vfs); 
 }
 if (haslength(this.typealiasespackage))
 {  
 // todo 支持自定义通配符 
 string[] typealiaspackagearray; 
 if (typealiasespackage.contains("*") && !typealiasespackage.contains(",")   
 && !typealiasespackage.contains(";")) 
 {   
 typealiaspackagearray = packagehelper.converttypealiasespackage(typealiasespackage);  
 } else {   typealiaspackagearray = tokenizetostringarray(this.typealiasespackage,  
  configurableapplicationcontext.config_location_delimiters);  
  }  
  if (typealiaspackagearray == null) {   
  throw new mybatisplusexception("not find typealiasespackage:" + typealiasespackage);  
  }  for (string packagetoscan : typealiaspackagearray) 
  {   
  configuration.gettypealiasregistry().registeraliases(packagetoscan,   
  typealiasessupertype == null ? object.class : typealiasessupertype);   
  if (logger.isdebugenabled())
  {    
  logger.debug("scanned package: '" + packagetoscan + "' for aliases");  
  }  
  } 
  }

 // todo 自定义枚举类扫描处理 
 if (haslength(this.typeenumspackage))
 {  
 set<class> classes = null;  
 if (typeenumspackage.contains("*") && !typeenumspackage.contains(",")  
 && !typeenumspackage.contains(";")) 
 {  
 classes = packagehelper.scantypepackage(typeenumspackage);  
 } else {   string[] typeenumspackagearray = tokenizetostringarray(this.typeenumspackage,   
 configurableapplicationcontext.config_location_delimiters);   
 if (typeenumspackagearray == null) 
 {   
 throw new mybatisplusexception("not find typeenumspackage:" + typeenumspackage);   
 }  
 classes = new hashset<class>();   
 for (string typepackage : typeenumspackagearray)
 {    
 classes.addall(packagehelper.scantypepackage(typepackage));  
 }  
 }  // 取得类型转换注册器  
 typehandlerregistry typehandlerregistry = configuration.gettypehandlerregistry();  
 for (class cls : classes) {   if (cls.isenum()) {    if (ienum.class.isassignablefrom(cls)) {   
 typehandlerregistry.register(cls.getname(), com.baomidou.mybatisplus.handlers.enumtypehandler.class.getcanonicalname());    } else {     
 // 使用原生 enumordinaltypehandler     typehandlerregistry.register(cls.getname(), org.apache.ibatis.type.enumordinaltypehandler.class.getcanonicalname());   
 }  
 }  } }
 if (!isempty(this.typealiases)) { 

 for (class<?> typealias : this.typealiases) 
 {   
 configuration.gettypealiasregistry().registeralias(typealias);   
 if (logger.isdebugenabled())
 {  
 logger.debug("registered type alias: '" + typealias + "'");  
 }  
 } }
 if (!isempty(this.plugins)) 
 {  
 for (interceptor plugin : this.plugins)
 {   
 configuration.addinterceptor(plugin);   
 if (logger.isdebugenabled()) 
 {    
 logger.debug("registered plugin: '" + plugin + "'");   
 }  
 } 
 }
 if (haslength(this.typehandlerspackage))
 {  
 string[] typehandlerspackagearray = tokenizetostringarray(this.typehandlerspackage,  
 configurableapplicationcontext.config_location_delimiters);  
 for (string packagetoscan : typehandlerspackagearray)
{  
 configuration.gettypehandlerregistry().register(packagetoscan);   
 if (logger.isdebugenabled()) {    
 logger.debug("scanned package: '" + packagetoscan + "' for type handlers");   
 }  
 } 
 }
 if (!isempty(this.typehandlers))
 {  
 for (typehandler<?> typehandler : this.typehandlers)
 {  
 configuration.gettypehandlerregistry().register(typehandler);  
 if (logger.isdebugenabled()) 
 {    
 logger.debug("registered type handler: '" + typehandler + "'");   
 }  } }
 if (this.databaseidprovider != null) {//fix #64 set databaseid before parse mapper xmls  
 try {   configuration.setdatabaseid(this.databaseidprovider.getdatabaseid(this.datasource));  
 } catch (sqlexception e) {   
 throw new nestedioexception("failed getting a databaseid", e); 
 } 
 }
 if (this.cache != null)
 {  
 configuration.addcache(this.cache); 
 }
 if (xmlconfigbuilder != null) 
 {  
 try 
 {   
 xmlconfigbuilder.parse();
   if (logger.isdebugenabled())
	 {   
	 logger.debug("parsed configuration file: '" + this.configlocation + "'");   
	 }  } catch (exception ex) 
	 {   
	 throw new nestedioexception("failed to parse config resource: " + this.configlocation, ex);  
	 } finally {   
	 errorcontext.instance().reset();  
	 }
	 }
 if (this.transactionfactory == null)
 {  this.transactionfactory = new springmanagedtransactionfactory(); 
 }
 configuration.setenvironment(new environment(this.environment, this.transactionfactory, this.datasource)); 
 // 设置元数据相关 
 globalconfigutils.setmetadata(datasource, globalconfig); sqlsessionfactory sqlsessionfactory = this.sqlsessionfactorybuilder.build(configuration); 
 // todo sqlrunner 
 sqlrunner.factory = sqlsessionfactory; // todo 缓存 sqlsessionfactory globalconfig.setsqlsessionfactory(sqlsessionfactory); // todo 设置全局参数属性 
 globalconfig.signglobalconfig(sqlsessionfactory); 
 if (!isempty(this.mapperlocations)) {  
 if (globalconfig.isrefresh()) {   
 //todo 设置自动刷新配置 减少配置   
 new mybatismapperrefresh(this.mapperlocations, sqlsessionfactory, 2,    
 2, true);  }  
 for (resource mapperlocation : this.mapperlocations)
 {  
 if (mapperlocation == null) {  
 continue;   
 }
   try {    
	 // todo 这里也换了噢噢噢噢  
	 xmlmapperbuilder xmlmapperbuilder = new xmlmapperbuilder(mapperlocation.getinputstream(),     
	 configuration, mapperlocation.tostring(), configuration.getsqlfragments());    
	 xmlmapperbuilder.parse();   
	 } catch (exception e) {   
	 throw new nestedioexception("failed to parse mapping resource: '" + mapperlocation + "'", e);   
 } finally {    
 errorcontext.instance().reset();   
 }
   if (logger.isdebugenabled())
	 {    
	 logger.debug("parsed mapper file: '" + mapperlocation + "'");  
	 } 
	 } 
	 } 
	 else { 
	 if (logger.isdebugenabled())
	 {  
	 logger.debug("property 'mapperlocations' was not specified or no matching resources found");  
	 } 
	 } 
	 return sqlsessionfactory;
	 }

上面代码主要做了如下事情:

  • 获取mybatisxmlconfigbuilder对象
  • 获取configuration对象-mybatisconfiguration
  • 配置对象configuration添加插件configuration.addinterceptor(plugin);
  • xmlconfigbuilder.parse()对configuration做进一步处理
  • 获取springmanagedtransactionfactory用来创建springmanagedtransaction
  • 获取一个defaultsqlsessionfactory实例对象
  • globalconfig.setsqlsessionfactory(sqlsessionfactory)中会创建mybatissqlsessiontemplate
  • 解析mapperlocation对应的一个个mapper配置文件,使用助手builderassistant的addmappedstatement方法将一个个结点添加配置对象中
  • 其他属性设置等等

也就是说,在mybatissqlsessionfactorybean.afterpropertiesset方法执行结束后,sqlsessionfactory、sqlsessiontemplate、configuration等都已存在!

【3】查询执行流程分析

示例代码如下:

list<employee > emps = employeemapper.selectpage(page, null);

如下图所示,此时我们获取到的employeemapper其实是个代理对象:

MyBatis Plus插件机制与执行流程原理分析详解

MyBatis Plus插件机制与执行流程原理分析详解

总结

到此这篇关于mybatis plus插件机制与执行流程原理分析的文章就介绍到这了,更多相关mybatis plus插件机制内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!