前言 探究MyBatis Plus提供的预定义CRUD接口的实现方式。
两种方式 MBP提供两种包含预定义CRUD的接口:
com.baomidou.mybatisplus.extension.service.IService
com.baomidou.mybatisplus.core.mapper.BaseMapper
其中IService接口是针对业务逻辑层的封装,并提供了批处理操作。BaseMapper则是对DAO层CRUD的封装。
BaseMapper BaseMapper的接口规范很简单,看代码就能明白,重点是了解MBP如何实现的BaseMapper。
在使用MyBatis的情况下,我们定义了Mapper接口,然后会在对应的XML文件中提供动态SQL及映射关系,或者直接在Mapper接口方法上添加注解,MyBatis将XML中的配置或者注解作为元数据进行解析,然后将解析后的SQL语句存至org.apache.ibatis.session.Configuration。MBP在MyBatis的基础上只做增强不做改变,则只要能够实现原pipeline将元数据解析成动态SQL存至org.apache.ibatis.session.Configuration即可。
MyBatis Plus的整体思路是使用自己的组件替换MyBatis中的组件,以实现自定义的逻辑。其中MybatisPlusAutoConfiguration类替代了MyBatis的自动配置类,这个类中包含MybatisPlusProperties属性。MybatisPlusProperties包含mapperLocations字段用于解析Mapper XML文件的位置,并汇总为Resource数组。
在MybatisPlusAutoConfiguration#sqlSessionFactory函数中,包含XML位置的Resource数组被设置到MybatisSqlSessionFactoryBean.mapperLocations下(MybatisSqlSessionFactoryBean也是MBP替换组件)。而后在MybatisSqlSessionFactoryBean#buildSqlSessionFactory函数中,XML文件被逐个读取并解析。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 if (this .mapperLocations != null ) { if (this .mapperLocations.length == 0 ) { LOGGER.warn(() -> "Property 'mapperLocations' was specified but matching resources are not found." ); } else { for (Resource mapperLocation : this .mapperLocations) { if (mapperLocation == null ) { continue ; } try { XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(), targetConfiguration, mapperLocation.toString(), targetConfiguration.getSqlFragments()); xmlMapperBuilder.parse(); } catch (Exception e) { throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'" , e); } finally { ErrorContext.instance().reset(); } LOGGER.debug(() -> "Parsed mapper file: '" + mapperLocation + "'" ); } } } else { LOGGER.debug(() -> "Property 'mapperLocations' was not specified." ); }
其中XMLMapperBuilder在解析过程中会调用XMLMapperBuilder#bindMapperForNamespace方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 private void bindMapperForNamespace () { String namespace = this .builderAssistant.getCurrentNamespace(); if (namespace != null ) { Class<?> boundType = null ; try { boundType = Resources.classForName(namespace); } catch (ClassNotFoundException var4) { } if (boundType != null && !this .configuration.hasMapper(boundType)) { this .configuration.addLoadedResource("namespace:" + namespace); this .configuration.addMapper(boundType); } } }
此时的configuration为MybatisSqlSessionFactoryBean传入的targetConfiguration,即MybatisConfiguration(MBP替换组件)。此时MybatisMapperRegistry#addMapper调用MybatisMapperRegistry#addMapper方法。
MybatisMapperRegistry也是一个MBP替换组件,继承并替换掉原本的MapperRegistry,其addMapper方法如下。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 public <T> void addMapper (Class<T> type) { if (type.isInterface()) { if (this .hasMapper(type)) { return ; } boolean loadCompleted = false ; try { this .knownMappers.put(type, new MybatisMapperProxyFactory(type)); MybatisMapperAnnotationBuilder parser = new MybatisMapperAnnotationBuilder(this .config, type); parser.parse(); loadCompleted = true ; } finally { if (!loadCompleted) { this .knownMappers.remove(type); } } } }
最终调用MBP自定义的MybatisMapperAnnotationBuilder#parse方法,如下。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 @Override public void parse () { String resource = type.toString(); if (!configuration.isResourceLoaded(resource)) { loadXmlResource(); configuration.addLoadedResource(resource); String mapperName = type.getName(); assistant.setCurrentNamespace(mapperName); parseCache(); parseCacheRef(); InterceptorIgnoreHelper.InterceptorIgnoreCache cache = InterceptorIgnoreHelper.initSqlParserInfoCache(type); for (Method method : type.getMethods()) { if (!canHaveStatement(method)) { continue ; } if (getAnnotationWrapper(method, false , Select.class, SelectProvider.class).isPresent() && method.getAnnotation(ResultMap.class) == null ) { parseResultMap(method); } try { InterceptorIgnoreHelper.initSqlParserInfoCache(cache, mapperName, method); parseStatement(method); } catch (IncompleteElementException e) { configuration.addIncompleteMethod(new MybatisMethodResolver(this , method)); } } try { if (GlobalConfigUtils.isSupperMapperChildren(configuration, type)) { parserInjector(); } } catch (IncompleteElementException e) { configuration.addIncompleteMethod(new InjectorResolver(this )); } } parsePendingMethods(); }
通过全局缓存工具GlobalConfigUtils获取ISqlInjector实例,调用ISqlInjector#inspectInject方法进行CRUD方法注入。在实现上,实际上是由AbstractSqlInjector实现了ISqlInjector接口,然后又由DefaultSqlInjector继承AbstractSqlInjector实现最终注入。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 public abstract class AbstractSqlInjector implements ISqlInjector { protected final Log logger = LogFactory.getLog(this .getClass()); @Override public void inspectInject (MapperBuilderAssistant builderAssistant, Class<?> mapperClass) { Class<?> modelClass = ReflectionKit.getSuperClassGenericType(mapperClass, Mapper.class, 0 ); if (modelClass != null ) { String className = mapperClass.toString(); Set<String> mapperRegistryCache = GlobalConfigUtils.getMapperRegistryCache(builderAssistant.getConfiguration()); if (!mapperRegistryCache.contains(className)) { TableInfo tableInfo = TableInfoHelper.initTableInfo(builderAssistant, modelClass); List<AbstractMethod> methodList = this .getMethodList(mapperClass, tableInfo); if (CollectionUtils.isNotEmpty(methodList)) { methodList.forEach(m -> m.inject(builderAssistant, mapperClass, modelClass, tableInfo)); } else { logger.debug(mapperClass.toString() + ", No effective injection method was found." ); } mapperRegistryCache.add(className); } } } public abstract List<AbstractMethod> getMethodList (Class<?> mapperClass,TableInfo tableInfo) ; }public class DefaultSqlInjector extends AbstractSqlInjector { @Override public List<AbstractMethod> getMethodList (Class<?> mapperClass, TableInfo tableInfo) { if (tableInfo.havePK()) { return Stream.of( new Insert(), new Delete(), new DeleteByMap(), new DeleteById(), new DeleteBatchByIds(), new Update(), new UpdateById(), new SelectById(), new SelectBatchByIds(), new SelectByMap(), new SelectCount(), new SelectMaps(), new SelectMapsPage(), new SelectObjs(), new SelectList(), new SelectPage() ).collect(toList()); } else { logger.warn(String.format("%s ,Not found @TableId annotation, Cannot use Mybatis-Plus 'xxById' Method." , tableInfo.getEntityType())); return Stream.of( new Insert(), new Delete(), new DeleteByMap(), new Update(), new SelectByMap(), new SelectCount(), new SelectMaps(), new SelectMapsPage(), new SelectObjs(), new SelectList(), new SelectPage() ).collect(toList()); } } }
其中每一个函数都是继承了com.baomidou.mybatisplus.core.injector.AbstractMethod的类,包含一个inject注入方法。
IService IService的实现在com.baomidou.mybatisplus.extension.service.impl.ServiceImpl。
IService依赖于Spring容器,而BaseMapper不依赖,原因是IService实例中会注入一个BaseMapper实例用于做CRUD操作,也就是上面的那一套。
IService还支持批量操作,这部分源码比较好看,调用链路是:com.baomidou.mybatisplus.extension.toolkit.SqlHelper#executeBatch -> org.apache.ibatis.session#flushStatements
参考文献 [1] https://blog.csdn.net/wjw465150/article/details/126896276 [2] https://blog.csdn.net/zzuhkp/article/details/120174101
后记 首发于 silencezheng.top ,转载请注明出处。