1. mybatis框架在如今各個IT公司的使用不用多說,這幾天看了mybatis的一些源碼,趕忙作個筆記. node
2. 看源碼從一個demo引入以下:sql
public class TestApp { private static SqlSessionFactory sqlSessionFactory; static { InputStream inputStream; String resource = "mybatis-config.xml"; try {
//獲取全局配置文件的數據流 inputStream = Resources.getResourceAsStream(resource); //獲取sqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } }
如上代碼獲取SQLSessionFactory實例對象,下來進入SqlSessionFactoryBuilder類中看其如何經過build方法建立SQLsessionFactory對象的: session
//外部調用的SQLSessionFactoryBuilder的build方法:
public SqlSessionFactory build(InputStream inputStream) { return build(inputStream, null, null); }
上面的方法調用下面的三個參數的build方法mybatis
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) { try {
//這裏建立的是mybatis全局配置文件的解析器 XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties); //解析器parser調用parse()方法對全局配置文件進行解析,返回一個Configuration對象,這個對象包含了mybatis全局配置文件中以及mapper文件中的全部配置信息
return build(parser.parse()); } catch (Exception e) { throw ExceptionFactory.wrapException("Error building SqlSession.", e); } finally { ErrorContext.instance().reset(); try { inputStream.close(); } catch (IOException e) { // Intentionally ignore. Prefer previous error. } } }
接着調用SqlSessionFactoryBuilder中的build(x)方法,建立一個defaultSQLSessionFactory對象返回給用戶app
// 入參是XMLConfigBuilder解析器解析後返回的Configuration對象,這個方法中建立一個defaultSqlSessonFactory對象給用戶,其中包含一個Configuration對象屬性
// 因此咱們獲取的SQLSessionFactory對象中就包含了項目中mybatis配置的全部信息
public SqlSessionFactory build(Configuration config) { return new DefaultSqlSessionFactory(config); }
上面的幾個步驟中建立了sqlSessionFactory對象,下來咱們看mybatis如何解析配置文件以及獲取Configuration對象:框架
3. mybaties解析配置文件ide
進入上面提到的XMLConfigBuilder parser.parse()方法中.源碼分析
//類XMLConfigBuilder //parsed第一次解析配置文件時默認爲FALSE,下面設置爲true,也就是配置文件只解析一次 public Configuration parse() { if (parsed) { throw new BuilderException("Each XMLConfigBuilder can only be used once."); } parsed = true;
//這裏解析開始解析配置文件,這裏的parser.evelNode("/configuration")是獲取元素"configuration"下面的全部信息,也就是主配置文件的根節點下的全部配置 parseConfiguration(parser.evalNode("/configuration")); //將配置文件解析完後,也就是對configuration對象組裝完成後,返回組裝(設值)後的configuration實例對象
return configuration; }
進入parseConfiguration()方法中,傳入的是配置文件的主要信息
private void parseConfiguration(XNode root) { try {
//這裏解析配置文件中配置的properties元素,其做用是若是存在properties元素的配置,則解析配置的property屬性,存放到configuration.setVariables(defaults)中去,具體看源碼這裏不詳述; propertiesElement(root.evalNode("properties")); //issue #117 read properties first //解析別名
typeAliasesElement(root.evalNode("typeAliases")); //解析插件
pluginElement(root.evalNode("plugins")); //這兩個暫時不懂
objectFactoryElement(root.evalNode("objectFactory")); objectWrapperFactoryElement(root.evalNode("objectWrapperFactory")); //解析全局配置屬性settings
settingsElement(root.evalNode("settings")); environmentsElement(root.evalNode("environments")); // read it after objectFactory and objectWrapperFactory issue #631 databaseIdProviderElement(root.evalNode("databaseIdProvider")); //解析類型轉換器
typeHandlerElement(root.evalNode("typeHandlers"));
//以上的解析結果都存放到了configuration的相關屬性中,下來這個解析配置的mappers節點以及其對應的mapper文件,咱們主要看下這個. mapperElement(root.evalNode("mappers")); } catch (Exception e) { throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e); } }
接入方法 mapperElement(xxxx)進行mapper文件的解析,其參數是經過root.evalNode("mappers");解析以後的<mappers>xxxxx</mappers>節點fetch
private void mapperElement(XNode parent) throws Exception { //判斷是否配置了mapper文件,若是沒有就直接退出
if (parent != null) {
//這裏獲取全部的mappers的子元素,而後遍歷挨個解析 for (XNode child : parent.getChildren()) { //解析以包方式進行的配置
if ("package".equals(child.getName())) { String mapperPackage = child.getStringAttribute("name"); configuration.addMappers(mapperPackage); } else {
//這裏是解析以文件方式配置的mapper,文件配置方式包括三種:resource,url,mapperClass;今天咱們主要看以resource方式配置的解析
//獲取文件配置路徑 String resource = child.getStringAttribute("resource"); String url = child.getStringAttribute("url"); String mapperClass = child.getStringAttribute("class");
//此種方式配置: <mapper resource="com/wfl/aries/mapper/UserMapper.xml"/> if (resource != null && url == null && mapperClass == null) { ErrorContext.instance().resource(resource);
//獲取mapper配置文件的流 InputStream inputStream = Resources.getResourceAsStream(resource);
//建立mapper解析器 XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments()); //解析mapper文件開始
mapperParser.parse(); } else if (resource == null && url != null && mapperClass == null) { ErrorContext.instance().resource(url); InputStream inputStream = Resources.getUrlAsStream(url); XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments()); mapperParser.parse(); } else if (resource == null && url == null && mapperClass != null) { Class<?> mapperInterface = Resources.classForName(mapperClass); configuration.addMapper(mapperInterface); } else { throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one."); } } } } }
進入mapper解析器ui
//類XMLMapperBuilder中 //解析mapper的方法 public void parse() { //判斷是否已經解析和加載過了,若是沒有則進行解析
if (!configuration.isResourceLoaded(resource)) {
//解析mapper傳入的參數是mapper文件的根節點 configurationElement(parser.evalNode("/mapper"));
//將該mapper的namespace添加到configuration的對象的一個set集合中去 configuration.addLoadedResource(resource);
//後續的mapper文件配置屬性和configuration對象關聯 bindMapperForNamespace(); } parsePendingResultMaps(); parsePendingChacheRefs(); parsePendingStatements(); }
具體的解析mapper文件的方法
private void configurationElement(XNode context) { try {
//獲取命名空間 String namespace = context.getStringAttribute("namespace"); //若是命名空間爲空則拋出異常
if (namespace.equals("")) { throw new BuilderException("Mapper's namespace cannot be empty"); } builderAssistant.setCurrentNamespace(namespace); cacheRefElement(context.evalNode("cache-ref")); cacheElement(context.evalNode("cache")); //處理參數映射配置
parameterMapElement(context.evalNodes("/mapper/parameterMap")); //處理結果映射配置
resultMapElements(context.evalNodes("/mapper/resultMap")); //處理sql片斷
sqlElement(context.evalNodes("/mapper/sql"));
//解析statment buildStatementFromContext(context.evalNodes("select|insert|update|delete")); } catch (Exception e) { throw new BuilderException("Error parsing Mapper XML. Cause: " + e, e); } }
解析statement的方法
//入參是一個statement的列表,也就是mapper中配置的全部的startement文件
private void buildStatementFromContext(List<XNode> list) { if (configuration.getDatabaseId() != null) { buildStatementFromContext(list, configuration.getDatabaseId()); } buildStatementFromContext(list, null); } //被上面的方法調用解析statement private void buildStatementFromContext(List<XNode> list, String requiredDatabaseId) { //循環變量解析每個statement
for (XNode context : list) {
//建立一個statement解析器 final XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, builderAssistant, context, requiredDatabaseId); try {
//解析單個statement statementParser.parseStatementNode(); } catch (IncompleteElementException e) { configuration.addIncompleteStatement(statementParser); } } }
//解析statement讀取配置文件中配置的statement的相關屬性,並取值以後建立一個mapperdStatement public void parseStatementNode() { String id = context.getStringAttribute("id"); String databaseId = context.getStringAttribute("databaseId"); if (!databaseIdMatchesCurrent(id, databaseId, this.requiredDatabaseId)) return; Integer fetchSize = context.getIntAttribute("fetchSize"); Integer timeout = context.getIntAttribute("timeout"); String parameterMap = context.getStringAttribute("parameterMap"); String parameterType = context.getStringAttribute("parameterType"); Class<?> parameterTypeClass = resolveClass(parameterType); String resultMap = context.getStringAttribute("resultMap"); String resultType = context.getStringAttribute("resultType"); String lang = context.getStringAttribute("lang"); LanguageDriver langDriver = getLanguageDriver(lang); Class<?> resultTypeClass = resolveClass(resultType); String resultSetType = context.getStringAttribute("resultSetType"); StatementType statementType = StatementType.valueOf(context.getStringAttribute("statementType", StatementType.PREPARED.toString())); ResultSetType resultSetTypeEnum = resolveResultSetType(resultSetType); String nodeName = context.getNode().getNodeName(); SqlCommandType sqlCommandType = SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH)); boolean isSelect = sqlCommandType == SqlCommandType.SELECT; boolean flushCache = context.getBooleanAttribute("flushCache", !isSelect); boolean useCache = context.getBooleanAttribute("useCache", isSelect); boolean resultOrdered = context.getBooleanAttribute("resultOrdered", false); // Include Fragments before parsing XMLIncludeTransformer includeParser = new XMLIncludeTransformer(configuration, builderAssistant); includeParser.applyIncludes(context.getNode()); // Parse selectKey after includes and remove them. processSelectKeyNodes(id, parameterTypeClass, langDriver); // Parse the SQL (pre: <selectKey> and <include> were parsed and removed) SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass); String resultSets = context.getStringAttribute("resultSets"); String keyProperty = context.getStringAttribute("keyProperty"); String keyColumn = context.getStringAttribute("keyColumn"); KeyGenerator keyGenerator; String keyStatementId = id + SelectKeyGenerator.SELECT_KEY_SUFFIX; keyStatementId = builderAssistant.applyCurrentNamespace(keyStatementId, true); if (configuration.hasKeyGenerator(keyStatementId)) { keyGenerator = configuration.getKeyGenerator(keyStatementId); } else { keyGenerator = context.getBooleanAttribute("useGeneratedKeys", configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType)) ? new Jdbc3KeyGenerator() : new NoKeyGenerator(); } builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType, fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass, resultSetTypeEnum, flushCache, useCache, resultOrdered, keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets); }
建立一個mapperdStatement並添加到configuration的mappedStatements的map集合中.
public MappedStatement addMappedStatement( String id, SqlSource sqlSource, StatementType statementType, SqlCommandType sqlCommandType, Integer fetchSize, Integer timeout, String parameterMap, Class<?> parameterType, String resultMap, Class<?> resultType, ResultSetType resultSetType, boolean flushCache, boolean useCache, boolean resultOrdered, KeyGenerator keyGenerator, String keyProperty, String keyColumn, String databaseId, LanguageDriver lang, String resultSets) { if (unresolvedCacheRef) throw new IncompleteElementException("Cache-ref not yet resolved"); id = applyCurrentNamespace(id, false); boolean isSelect = sqlCommandType == SqlCommandType.SELECT; MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration, id, sqlSource, sqlCommandType); statementBuilder.resource(resource); statementBuilder.fetchSize(fetchSize); statementBuilder.statementType(statementType); statementBuilder.keyGenerator(keyGenerator); statementBuilder.keyProperty(keyProperty); statementBuilder.keyColumn(keyColumn); statementBuilder.databaseId(databaseId); statementBuilder.lang(lang); statementBuilder.resultOrdered(resultOrdered); statementBuilder.resulSets(resultSets); setStatementTimeout(timeout, statementBuilder); setStatementParameterMap(parameterMap, parameterType, statementBuilder); setStatementResultMap(resultMap, resultType, resultSetType, statementBuilder); setStatementCache(isSelect, flushCache, useCache, currentCache, statementBuilder); MappedStatement statement = statementBuilder.build(); configuration.addMappedStatement(statement); return statement; }
解析完全部的mapper以及其中的statement以後,全部的解析就到此結束,返回configuration對象給SqlSessionFactoryBuilder對象,建立DefaultSqlSessionFactory.
注: 其中SqlSessionFactory是接口,DefaultSqlSessionFactory實現了其SQLSessionFactory因此最後建立的是DefaultSqlSessionFactory
由此獲取到了sessionFactory;