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主要邏輯點
- mybaties自動配置流程
- mybaties mapper接口動態代理注入到spring中流程
- sql執行流程
下面就圍繞這三掉來分析下mybaties的源碼和執行流程
mybaties自動配置流程
mybaties mapper接口動態代理注入到spring中流程
sql執行流程
圖中根據執行邏輯分成了三大塊。
藍色部分:通過調用MapperFactoryBean的getObject方法生成mapper對應的動態代理。
紅色部分:調用mapper方法的時候,觸發對應動態代理攔截對應的方法。
綠色部分:
sqlsession執行一條sql的邏輯。主要先從configration中獲取對應的MappedStatement,然后創建
Executor執行器(默認是SimpleExecutor),執行器流程:
- 獲取StatementHandler,先執行jdbc的prepare,
- 然后用ParameterHandler把mapper方法中傳入的參數(對象或者值)解析后設置到Jdbc的statement中。
- 執行jdbc execute方法,去執行具體的sql。
- ResultSetHandler調用handleCursorResultSets方法處理查詢返回的結果,主要是進行對象的映射處理。最后把結果再依次返回。
配置入口類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);