首页 > 代码库 > mybatis源码分析(一)
mybatis源码分析(一)
mybatis源码分析(sqlSessionFactory生成过程)
1. mybatis框架在现在各个IT公司的使用不用多说,这几天看了mybatis的一些源码,赶紧做个笔记.
2. 看源码从一个demo引入如下:
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对象的:
//外部调用的SQLSessionFactoryBuilder的build方法:
public SqlSessionFactory build(InputStream inputStream) { return build(inputStream, null, null); }
上面的方法调用下面的三个参数的build方法
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对象返回给用户
// 入参是XMLConfigBuilder解析器解析后返回的Configuration对象,这个方法中创建一个defaultSqlSessonFactory对象给用户,其中包含一个Configuration对象属性
// 所以我们获取的SQLSessionFactory对象中就包含了项目中mybatis配置的所有信息
public SqlSessionFactory build(Configuration config) { return new DefaultSqlSessionFactory(config); }
上面的几个步骤中创建了sqlSessionFactory对象,下来我们看mybatis如何解析配置文件以及获取Configuration对象:
3. mybaties解析配置文件
进入上面提到的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>节点
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解析器
//类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;
mybatis源码分析(一)