<返回更多

彻底看懂springboot mybaties源码流程

2022-11-07  今日头条  奋斗的架构师
加入收藏

mybaties核心组件概念

Configuration:用于描述 MyBatis 主配置文件信息,MyBatis 框架在启动时自动配置类中,会加载mApper配置文件,将配置信息转换为 Configuration 对象,然后把该对象传入给SQLSessionFactory供后续使用。

sqlSession:面向用户的 API,是 MyBatis 与数据库交互的接口。

Executor:Sql 执行器,用于和数据库交互。SqlSession 可以理解为 Executor 组件的外观(外观模式),真正执行 SQL 的是 Executor 组件。

Mappedstatement:用于描述 SQL 配置信息,MyBatis 框架启动时,XML 文件或者注解配置的 SQL信息会被转换为 MappedStatement 对象注册到 Configuration 组件中。

StatementHandler:封装了对 JDBC 中 Statement 对象的操作,包括为 Statement 参数占位符设置值,通过 Statement 对象执行 SQL语句。

TypeHandler:类型处理器,用于 JAVA 类型与 JDBC 类型之间的转换。

ParameterHandler:用于处理 SQL 中的参数占位符,为参数占位符设置值。

ResultSetHandler:封装了对 ResultSet 对象的处理逻辑,将结果集转换为 Java 实体对象。

mybaties主要逻辑点

  1. mybaties自动配置流程
  2. mybaties mapper接口动态代理注入到spring中流程
  3. sql执行流程

 

下面就围绕这三掉来分析下mybaties的源码和执行流程

mybaties自动配置流程


 

mybaties mapper接口动态代理注入到spring中流程


 

sql执行流程


 

图中根据执行逻辑分成了三大块。

蓝色部分:通过调用MapperFactoryBean的getObject方法生成mapper对应的动态代理。

红色部分:调用mapper方法的时候,触发对应动态代理拦截对应的方法。

绿色部分:

sqlsession执行一条sql的逻辑。主要先从configration中获取对应的MappedStatement,然后创建

Executor执行器(默认是SimpleExecutor),执行器流程:

 

  1. 获取StatementHandler,先执行jdbc的prepare,
  2. 然后用ParameterHandler把mapper方法中传入的参数(对象或者值)解析后设置到Jdbc的statement中。
  3. 执行jdbc execute方法,去执行具体的sql。
  4. ResultSetHandler调用handleCursorResultSets方法处理查询返回的结果,主要是进行对象的映射处理。最后把结果再依次返回。
mybaties自动配置流程

 

配置入口类MybatisAutoConfiguration

@Bean@ConditionalOnMissingBeanpublic SqlSessionFactory sqlSessionFactory(DataSource DataSource) throws Exception {SqlSessionFactoryBean factory = new SqlSessionFactoryBean();factory.setDataSource(dataSource);factory.setVfs(SpringBootVFS.class);if (StringUtils.hasText(this.properties.getConfigLocation())) {factory.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));applyConfiguration(factory);if (this.properties.getConfigurationProperties() != null) {factory.setConfigurationProperties(this.properties.getConfigurationProperties());if (!ObjectUtils.isEmpty(this.interceptors)) {factory.setPlugins(this.interceptors);if (this.databaseIdProvider != null) {factory.setDatabaseIdProvider(this.databaseIdProvider);if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {factory.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());if (this.properties.getTypeAliasesSuperType() != null) {factory.setTypeAliasesSuperType(this.properties.getTypeAliasesSuperType());if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {factory.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());if (!ObjectUtils.isEmpty(this.typeHandlers)) {factory.setTypeHandlers(this.typeHandlers);if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {factory.setMapperLocations(this.properties.resolveMapperLocations());Set factoryPropertyNames = Stream.of(new BeanWrapperImpl(SqlSessionFactoryBean.class).getPropertyDescriptors()).map(PropertyDescriptor::getName).collect(Collectors.toSet());Class defaultLanguageDriver = this.properties.getDefaultScriptingLanguageDriver();if (factoryPropertyNames.contains("scriptingLanguageDrivers") && !ObjectUtils.isEmpty(this.languageDrivers)) {// Need to mybatis-spring 2.0.2+factory.setScriptingLanguageDrivers(this.languageDrivers);if (defaultLanguageDriver == null && this.languageDrivers.length == 1) {defaultLanguageDriver = this.languageDrivers[0].getClass();if (factoryPropertyNames.contains("defaultScriptingLanguageDriver")) {// Need to mybatis-spring 2.0.2+factory.setDefaultScriptingLanguageDriver(defaultLanguageDriver);return factory.getObject();@Bean@ConditionalOnMissingBeanpublic SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {ExecutorType executorType = this.properties.getExecutorType();if (executorType != null) {return new SqlSessionTemplate(sqlSessionFactory, executorType);} else {return new SqlSessionTemplate(sqlSessionFactory);

这个类没啥好说的,主要看sqlSessionFactory,它是通过SqlSessionFactoryBean的getObject生成的。

继续看getObject方法,里面主要就是调用了buildSqlSessionFactory方法

protected SqlSessionFactory buildSqlSessionFactory() throws Exception {...省略不关心代码for (Resource mapperLocation : this.mapperLocations) {if (mapperLocation == null) {continue;try {// 解析mapper对应的xml文件,它会把xml解析成一个个的MappedStatement,即每个查询标签都会被解析成一个MappedStatement// 解析完后,会间接存入Configuration中。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 + "'");...省略不关心代码// 创建sqlSessionFactory类,并把targetConfiguration作为参数return this.sqlSessionFactoryBuilder.build(targetConfiguration);

经过此步骤后,mybaties中mapper的解析工作已经完成了,后续就可以通过动态代理拦截方法,去执行sql了。

mybaties mapper接口动态代理注入到spring中流程

MapperScan

@Import(MapperScannerRegistrar.class)@Repeatable(MapperScans.class)public @interface MapperScan {

MapperScannerRegistrar

@Overridepublic void registerBeanDefinitions(annotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {AnnotationAttributes mapperScanAttrs = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(MapperScan.class.getName()));if (mapperScanAttrs != null) {registerBeanDefinitions(importingClassMetadata, mapperScanAttrs, registry,generateBaseBeanName(importingClassMetadata, 0));void registerBeanDefinitions(AnnotationMetadata annoMeta, AnnotationAttributes annoAttrs,BeanDefinitionRegistry registry, String beanName) {// 指定BeanDefinition对应的类,这里是MapperScannerConfigurer,这个类很重要后续会解释BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MapperScannerConfigurer.class);builder.addPropertyValue("processPropertyPlaceHolders", true);... 省去不重要代码// 设置mapperFactoryBeanClass属性,这个是MapperFactoryBean,最终就是调用它的getObject方法,生成对应mapper的动态代理,//,然后注入到spring中的Class mapperFactoryBeanClass = annoAttrs.getClass("factoryBean");if (!MapperFactoryBean.class.equals(mapperFactoryBeanClass)) {builder.addPropertyValue("mapperFactoryBeanClass", mapperFactoryBeanClass);// 可以直接定义覆盖默认的sqlSessionTemplateRefString sqlSessionTemplateRef = annoAttrs.getString("sqlSessionTemplateRef");if (StringUtils.hasText(sqlSessionTemplateRef)) {builder.addPropertyValue("sqlSessionTemplateBeanName", annoAttrs.getString("sqlSessionTemplateRef"));// 可以直接定义覆盖默认的sqlSessionFactory,比如配置多数据源的时候,可以定义自己的fatoryString sqlSessionFactoryRef = annoAttrs.getString("sqlSessionFactoryRef");if (StringUtils.hasText(sqlSessionFactoryRef)) {builder.addPropertyValue("sqlSessionFactoryBeanName", annoAttrs.getString("sqlSessionFactoryRef"));// 要扫描的mapper路径,只会把该路径下的mapper注册成动态代理List basePackages = new ArrayList<>();basePackages.addAll(Arrays.stream(annoAttrs.getStringArray("value")).filter(StringUtils::hasText).collect(Collectors.toList()));basePackages.addAll(Arrays.stream(annoAttrs.getStringArray("basePackages")).filter(StringUtils::hasText).collect(Collectors.toList()));basePackages.addAll(Arrays.stream(annoAttrs.getClassArray("basePackageClasses")).map(ClassUtils::getPackageName).collect(Collectors.toList()));if (basePackages.isEmpty()) {basePackages.add(getDefaultBasePackage(annoMeta));String lazyInitialization = annoAttrs.getString("lazyInitialization");if (StringUtils.hasText(lazyInitialization)) {builder.addPropertyValue("lazyInitialization", lazyInitialization);builder.addPropertyValue("basePackage", StringUtils.collectionToCommaDelimitedString(basePackages));// 把MapperScannerConfigurer类生成对应,并且注入到spring容器中registry.registerBeanDefinition(beanName, builder.getBeanDefinition());

上面方法会把MapperScannerConfigurer实例化,并且注入到容器中。

MapperScannerConfigurer类创建成功后会调用它的postProcessBeanDefinitionRegistry方法,该方法属于BeanDefinitionRegistryPostProcessor接口,注册了BeanDefinition后,spring会触发该方法,所以再分析该方法。

MapperScannerConfigurer

@Overridepublic void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {if (this.processPropertyPlaceHolders) {processPropertyPlaceHolders();// 核心类,主要是扫描指定的mapper路径下所有的mapper接口,然后注入到spring的时候,注入的名字还是接口名// 但是注入的实际类替换成了MapperFactoryBean,该类是一个FactoryBean,当调用它的getObject的时候,会生成// 对应接口的动态代理ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);scanner.setAddToConfig(this.addToConfig);scanner.setAnnotationClass(this.annotationClass);scanner.setMarkerInterface(this.markerInterface);scanner.setSqlSessionFactory(this.sqlSessionFactory);scanner.setSqlSessionTemplate(this.sqlSessionTemplate);scanner.setSqlSessionFactoryBeanName(this.sqlSessionFactoryBeanName);scanner.setSqlSessionTemplateBeanName(this.sqlSessionTemplateBeanName);scanner.setResourceLoader(this.applicationContext);scanner.setBeanNameGenerator(this.nameGenerator);// 设置MapperFactoryBean类scanner.setMapperFactoryBeanClass(this.mapperFactoryBeanClass);if (StringUtils.hasText(lazyInitialization)) {scanner.setLazyInitialization(Boolean.valueOf(lazyInitialization));scanner.registerFilters();// 调用scan,把对应包路径下的所有类,注入到spring容器中scanner.scan(StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));

ClassPathMapperScanner继承了ClassPathBeanDefinitionScanner,该类的san方法可以扫描指定路径下的所有类,并把他们注入到spring容器中。

经过上面这个方法后,指定mapper路径下的所有接口,会以动态代理的方式注入到spring容器中。

sql执行流程

上面分析了动态代理生成的核心类是MapperFactoryBean的getObject方法,这里先分析动态代理生成逻辑

MapperFactoryBean

public T getObject() throws Exception {return getSqlSession().getMapper(this.mapperInterface);

会调用到

SqlSessionTemplate

public T getMapper(Class type) {// 这里获取Configuration类,然后调用getMapper方法。return getConfiguration().getMapper(type, this);

最后会调用到这里,创建动态代理

MapperProxyFactory

protected T newInstance(MapperProxy mapperProxy) {return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);public T newInstance(SqlSession sqlSession) {final MapperProxy mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache);return newInstance(mapperProxy);

上面可以看到动态代理拦截方法类是MapperProxy,当执行动态代理对应方法的时候,会先执行该类的拦截方法invoke -> cachedInvoker ,最后调用到的拦截方法是MapperMethod的execute,如下:

MapperMethod

public Object execute(SqlSession sqlSession, Object[] args) {Object result;// 根据不同的类型,来不行不同的方法switch (command.getType()) {case INSERT: {Object param = method.convertArgsToSqlCommandParam(args);result = rowCountResult(sqlSession.insert(command.getName(), param));break;case UPDATE: {Object param = method.convertArgsToSqlCommandParam(args);result = rowCountResult(sqlSession.update(command.getName(), param));break;case DELETE: {Object param = method.convertArgsToSqlCommandParam(args);result = rowCountResult(sqlSession.delete(command.getName(), param));break;case SELECT:if (method.returnsVoid() && method.hasResultHandler()) {executeWithResultHandler(sqlSession, args);result = null;} else if (method.returnsMany()) {result = executeForMany(sqlSession, args);} else if (method.returnsMap()) {result = executeForMap(sqlSession, args);} else if (method.returnsCursor()) {result = executeForCursor(sqlSession, args);} else {Object param = method.convertArgsToSqlCommandParam(args);result = sqlSession.selectOne(command.getName(), param);if (method.returnsOptional()&& (result == null || !method.getReturnType().equals(result.getClass()))) {result = Optional.ofNullable(result);break;case FLUSH:result = sqlSession.flushStatements();break;default:throw new BindingException("Unknown execution method for: " + command.getName());if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {throw new BindingException("Mapper method '" + command.getName()+ " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");return result;private Object executeForMany(SqlSession sqlSession, Object[] args) {List result;Object param = method.convertArgsToSqlCommandParam(args);if (method.hasRowBounds()) {RowBounds rowBounds = method.extractRowBounds(args);// 执行sqlSession的方法,其实这里是sqlSessionTemplate,具体可以看前面传入的参数result = sqlSession.selectList(command.getName(), param, rowBounds);} else {result = sqlSession.selectList(command.getName(), param);return result;

会根据不同的类型来执行不同的处理sql方法,这里以executeForMany为入口分析,调用了sqlSessionTemplate的selectList方法。如下:

SqlSessionTemplate

public List selectList(String statement, Object parameter, RowBounds rowBounds) {return this.sqlSessionProxy.selectList(statement, parameter, rowBounds);

sqlSessionProxy是什么东西?

其实这是一个SqlSession的代理类,主要作用是执行具体sql之前先opensession获取一个sqlsession,sql执行完后再closesession。

具体代码如下:

SqlSessionTemplate

public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory, ExecutorType executorType,PersistenceExceptionTranslator exceptionTranslator) {notNull(sqlSessionFactory, "Property 'sqlSessionFactory' is required");notNull(executorType, "Property 'executorType' is required");this.sqlSessionFactory = sqlSessionFactory;this.executorType = executorType;this.exceptionTranslator = exceptionTranslator;// 创建sqlSession动态代理this.sqlSessionProxy = (SqlSession) newProxyInstance(SqlSessionFactory.class.getClassLoader(),new Class[] { SqlSession.class }, new SqlSessionInterceptor());// 动态代理拦截方法private class SqlSessionInterceptor implements InvocationHandler {@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {// 先获取sqlsession,里面就是调用了SqlSessionFactory的openSession方法。SqlSession sqlSession = getSqlSession(SqlSessionTemplate.this.sqlSessionFactory,SqlSessionTemplate.this.executorType, SqlSessionTemplate.this.exceptionTranslator);try {// 调用SqlSession具体的方法Object result = method.invoke(sqlSession, args);if (!isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) {// force commit even on non-dirty sessions because some databases require// a commit/rollback before calling close()sqlSession.commit(true);return result;} catch (Throwable t) {Throwable unwrapped = unwrapThrowable(t);if (SqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) {// release the connection to avoid a deadlock if the translator is no loaded. See issue #22closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);sqlSession = null;Throwable translated = SqlSessionTemplate.this.exceptionTranslator.translateExceptionIfPossible((PersistenceException) unwrapped);if (translated != null) {unwrapped = translated;throw unwrapped;} finally {if (sqlSession != null) {// 收尾工作,管理sessioncloseSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);

跟踪的getSqlSession方法,会发现SqlSession的实现类是DefaultSqlSession,它的selectList方法如下

DefaultSqlSession

@Overridepublic List selectList(String statement, Object parameter, RowBounds rowBounds) {try {// 获取xml解析出来的MappedStatementMappedStatement ms = configuration.getMappedStatement(statement);// 调用执行器的query方法,这里的Executor默认的是SimpleExecutorreturn executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);} catch (Exception e) {throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);} finally {ErrorContext.instance().reset();

经过一系列调用最终会调用到如下代码

SimpleExecutor

@Overridepublic List doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {Statement stmt = null;try {// 获取Configuration类Configuration configuration = ms.getConfiguration();// 创建StatementHandler,默认它的实现类是PreparedStatementHandler,newStatementHandler方法中// 还会调用interceptorChain.pluginAll给StatementHandler设置拦截器配置,这样后续就可以定义StatementHandler// 对应的拦截器了。StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);// 最终会执行JDBC中prepare操作stmt = prepareStatement(handler, ms.getStatementLog());// 执行查询操作return handler.query(stmt, resultHandler);} finally {closeStatement(stmt);private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {Statement stmt;// 最终通过数据源获取一个JDBC连接Connection connection = getConnection(statementLog);// 最终也会执行JDBC的prepare操作stmt = handler.prepare(connection, transaction.getTimeout());// 这里的最终会调用到ParameterHandler的setParameters方法,把mapper方法中的参数转换后,传入// JDBC的statement中。handler.parameterize(stmt);return stmt;

继续看query方法,这里的handler是PreparedStatementHandler

如下:

@Overridepublic List query(Statement statement, ResultHandler resultHandler) throws SQLException {PreparedStatement ps = (PreparedStatement) statement;// jdbc具体执行方法ps.execute();// 调用ResultSethandler进行查询结果数据处理,主要做数据对象映射,然后把处理后的数据返回。return resultSetHandler.handleResultSets(ps);@Overridepublic void parameterize(Statement statement) throws SQLException {// 这个就是上面提到的,“把mapper方法中的参数转换后,传入// JDBC的statement中”parameterHandler.setParameters((PreparedStatement) statement);

声明:本站部分内容来自互联网,如有版权侵犯或其他问题请与我们联系,我们将立即删除或处理。
▍相关推荐
更多资讯 >>>