今天來具體看一下如何解析environments
//XMLConfigBuilder javascript
Java代碼java
- private void parseConfiguration(XNode root)
- {
- try
- {
- propertiesElement(root.evalNode("properties"));
- typeAliasesElement(root.evalNode("typeAliases"));
- pluginElement(root.evalNode("plugins"));
- objectFactoryElement(root.evalNode("objectFactory"));
- objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
- settingsElement(root.evalNode("settings"));
- //解析environments
- environmentsElement(root.evalNode("environments"));
- databaseIdProviderElement(root.evalNode("databaseIdProvider"));
- typeHandlerElement(root.evalNode("typeHandlers"));
- mapperElement(root.evalNode("mappers"));
- }
- catch(Exception e)
- {
- throw new BuilderException((new StringBuilder()).append("Error parsing SQL Mapper Configuration. Cause: ").append(e).toString(), e);
- }
- }
- //解析environments
- private void environmentsElement(XNode context)
- throws Exception
- {
- if(context != null)
- {
- if(C == null)
- environment = context.getStringAttribute("default");
- Iterator i$ = context.getChildren().iterator();
- //遍歷environments的child節點environment,並解析
- do
- {
- if(!i$.hasNext())
- break;
- XNode child = (XNode)i$.next();
- String id = child.getStringAttribute("id");
- //若是environment的id屬性,與environments的default相同時,才解析
- if(isSpecifiedEnvironment(id))
- {
- //解析transactionManager
- TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
- //解析dataSource
- DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));
- javax.sql.DataSource dataSource = dsFactory.getDataSource();
- org.apache.ibatis.mapping.Environment.Builder environmentBuilder = (new org.apache.ibatis.mapping.Environment.Builder(id)).transactionFactory(txFactory).dataSource(dataSource);
- configuration.setEnvironment(environmentBuilder.build());
- }
- } while(true);
- }
- }
//解析transactionManager
先看configuration的構造,啓動有JDBC,POOLED類型的映射關係,這個在解析environment節點時,須要用到 下載sql
Java代碼數據庫
- typeAliasRegistry.registerAlias("JDBC", org/apache/ibatis/transaction/jdbc/JdbcTransactionFactory);
- typeAliasRegistry.registerAlias("POOLED", org/apache/ibatis/datasource/pooled/PooledDataSourceFactory);
Java代碼apache
- public Configuration()
- {
- safeRowBoundsEnabled = false;
- safeResultHandlerEnabled = true;
- mapUnderscoreToCamelCase = false;
- aggressiveLazyLoading = true;
- multipleResultSetsEnabled = true;
- useGeneratedKeys = false;//容許JDBC支持生成的鍵
- useColumnLabel = true;
- cacheEnabled = true;//全局的映射器啓用或禁用緩存
- callSettersOnNulls = false;
- localCacheScope = LocalCacheScope.SESSION;//本地一級緩存做用域
- jdbcTypeForNull = JdbcType.OTHER;
- lazyLoadTriggerMethods = new HashSet(Arrays.asList(new String[] {
- "equals", "clone", "hashCode", "toString"
- }));
- defaultExecutorType = ExecutorType.SIMPLE;
- autoMappingBehavior = AutoMappingBehavior.PARTIAL;
- variables = new Properties();
- objectFactory = new DefaultObjectFactory();//默認ObjectFactory
- objectWrapperFactory = new DefaultObjectWrapperFactory();//默認DefaultObjectWrapperFactory
- mapperRegistry = new MapperRegistry(this);
- lazyLoadingEnabled = false;
- interceptorChain = new InterceptorChain();//插件鏈
- typeHandlerRegistry = new TypeHandlerRegistry();//類型處理註冊器
- typeAliasRegistry = new TypeAliasRegistry();//類型別名註冊器
- languageRegistry = new LanguageDriverRegistry();
- //mappedStatements Map
- mappedStatements = new StrictMap("Mapped Statements collection");
- //mappedStatements,method,二級緩存
- caches = new StrictMap("Caches collection");
- //MapperInterface 方法返回結果類型Map
- resultMaps = new StrictMap("Result Maps collection");
- //MapperInterface 方法參數類型Map
- parameterMaps = new StrictMap("Parameter Maps collection");
- //主鍵生成器Map
- keyGenerators = new StrictMap("Key Generators collection");
- loadedResources = new HashSet();
- //Mapper.xml 中statement片斷
- sqlFragments = new StrictMap("XML fragments parsed from previous mappers");
- //未解析處理的statements
- incompleteStatements = new LinkedList();
- //未解析處理的CacheRefs
- incompleteCacheRefs = new LinkedList();
- //未解析處理的ResultMaps
- incompleteResultMaps = new LinkedList();
- //未解析處理的Methods
- incompleteMethods = new LinkedList();
- cacheRefMap = new HashMap();
- typeAliasRegistry.registerAlias("JDBC", org/apache/ibatis/transaction/jdbc/JdbcTransactionFactory);
- typeAliasRegistry.registerAlias("MANAGED", org/apache/ibatis/transaction/managed/ManagedTransactionFactory);
- typeAliasRegistry.registerAlias("JNDI", org/apache/ibatis/datasource/jndi/JndiDataSourceFactory);
- typeAliasRegistry.registerAlias("POOLED", org/apache/ibatis/datasource/pooled/PooledDataSourceFactory);
- typeAliasRegistry.registerAlias("UNPOOLED", org/apache/ibatis/datasource/unpooled/UnpooledDataSourceFactory);
- typeAliasRegistry.registerAlias("PERPETUAL", org/apache/ibatis/cache/impl/PerpetualCache);
- typeAliasRegistry.registerAlias("FIFO", org/apache/ibatis/cache/decorators/FifoCache);
- typeAliasRegistry.registerAlias("LRU", org/apache/ibatis/cache/decorators/LruCache);
- typeAliasRegistry.registerAlias("SOFT", org/apache/ibatis/cache/decorators/SoftCache);
- typeAliasRegistry.registerAlias("WEAK", org/apache/ibatis/cache/decorators/WeakCache);
- typeAliasRegistry.registerAlias("VENDOR", org/apache/ibatis/mapping/VendorDatabaseIdProvider);
- typeAliasRegistry.registerAlias("XML", org/apache/ibatis/scripting/xmltags/XMLLanguageDriver);
- typeAliasRegistry.registerAlias("RAW", org/apache/ibatis/scripting/defaults/RawLanguageDriver);
- typeAliasRegistry.registerAlias("SLF4J", org/apache/ibatis/logging/slf4j/Slf4jImpl);
- typeAliasRegistry.registerAlias("COMMONS_LOGGING", org/apache/ibatis/logging/commons/JakartaCommonsLoggingImpl);
- typeAliasRegistry.registerAlias("LOG4J", org/apache/ibatis/logging/log4j/Log4jImpl);
- typeAliasRegistry.registerAlias("JDK_LOGGING", org/apache/ibatis/logging/jdk14/Jdk14LoggingImpl);
- typeAliasRegistry.registerAlias("STDOUT_LOGGING", org/apache/ibatis/logging/stdout/StdOutImpl);
- typeAliasRegistry.registerAlias("NO_LOGGING", org/apache/ibatis/logging/nologging/NoLoggingImpl);
- typeAliasRegistry.registerAlias("CGLIB", org/apache/ibatis/executor/loader/CglibProxyFactory);
- typeAliasRegistry.registerAlias("JAVASSIST", org/apache/ibatis/executor/loader/JavassistProxyFactory);
- languageRegistry.setDefaultDriverClass(org/apache/ibatis/scripting/xmltags/XMLLanguageDriver);
- languageRegistry.register(org/apache/ibatis/scripting/defaults/RawLanguageDriver);
- }
從上能夠看出JDBC,POOLED類型別名的映射關係以下:
JDBC,JdbcTransactionFactory 下載
POOLED,PooledDataSourceFactory
緩存
Java代碼app
- <environments default="development">
- <environment id="development">
- <transactionManager type="JDBC" />
- <dataSource type="POOLED">
- <property name="driver" value="${driver}" />
- <property name="url" value="${url}" />
- <property name="username" value="${username}" />
- <property name="password" value="${password}" />
- </dataSource>
- </environment>
- </environments>
Java代碼ide
- private TransactionFactory transactionManagerElement(XNode context)
- throws Exception
- {
- if(context != null)
- {
- String type = context.getStringAttribute("type");
- Properties props = context.getChildrenAsProperties();
- //從類型解決器中,獲取type對應的類型的實例,從上面的配置來看
- //實際爲JdbcTransactionFactory
- TransactionFactory factory = (TransactionFactory)resolveClass(type).newInstance();
- //設置JdbcTransactionFactory屬性
- factory.setProperties(props);
- return factory;
- } else
- {
- throw new BuilderException("Environment declaration requires a TransactionFactory.");
- }
- }
//JdbcTransactionFactory ui
Java代碼this
下載
- public class JdbcTransactionFactory
- implements TransactionFactory
- {
- public void setProperties(Properties properties)
- {
- }
- //根據數據鏈接新建事務
- public Transaction newTransaction(Connection conn)
- {
- return new JdbcTransaction(conn);
- }
- //根據數據源和事務級別和是否自動提交,新建事務
- public Transaction newTransaction(DataSource ds, TransactionIsolationLevel level, boolean autoCommit)
- {
- return new JdbcTransaction(ds, level, autoCommit);
- }
- }
//TransactionFactory
Java代碼
- public interface TransactionFactory
- {
- public abstract void setProperties(Properties properties);
- public abstract Transaction newTransaction(Connection connection);
- public abstract Transaction newTransaction(DataSource datasource, TransactionIsolationLevel transactionisolationlevel, boolean flag);
- }
如今來看一下jdbc事務
Java代碼
下載
- public class JdbcTransaction
- implements Transaction
- {
- private static final Log log = LogFactory.getLog(org/apache/ibatis/transaction/jdbc/JdbcTransaction);
- protected Connection connection;//數據庫鏈接
- protected DataSource dataSource;//數據源
- protected TransactionIsolationLevel level;//事務級別
- protected boolean autoCommmit;//自動提交屬性
-
- public JdbcTransaction(DataSource ds, TransactionIsolationLevel desiredLevel, boolean desiredAutoCommit)
- {
- dataSource = ds;
- level = desiredLevel;
- autoCommmit = desiredAutoCommit;
- }
-
- public JdbcTransaction(Connection connection)
- {
- this.connection = connection;
- }
-
- public Connection getConnection()
- throws SQLException
- {
- if(connection == null)
- openConnection();
- return connection;
- }
-
- public void commit()
- throws SQLException
- {
- if(connection != null && !connection.getAutoCommit())
- {
- if(log.isDebugEnabled())
- log.debug((new StringBuilder()).append("Committing JDBC Connection [").append(connection).append("]").toString());
- connection.commit();
- }
- }
-
- public void rollback()
- throws SQLException
- {
- if(connection != null && !connection.getAutoCommit())
- {
- if(log.isDebugEnabled())
- log.debug((new StringBuilder()).append("Rolling back JDBC Connection [").append(connection).append("]").toString());
- connection.rollback();
- }
- }
-
- public void close()
- throws SQLException
- {
- if(connection != null)
- {
- resetAutoCommit();
- if(log.isDebugEnabled())
- log.debug((new StringBuilder()).append("Closing JDBC Connection [").append(connection).append("]").toString());
- connection.close();
- }
- }
-
- protected void setDesiredAutoCommit(boolean desiredAutoCommit)
- {
- try
- {
- if(connection.getAutoCommit() != desiredAutoCommit)
- {
- if(log.isDebugEnabled())
- log.debug((new StringBuilder()).append("Setting autocommit to ").append(desiredAutoCommit).append(" on JDBC Connection [").append(connection).append("]").toString());
- connection.setAutoCommit(desiredAutoCommit);
- }
- }
- catch(SQLException e)
- {
- throw new TransactionException((new StringBuilder()).append("Error configuring AutoCommit. Your driver may not support getAutoCommit() or setAutoCommit(). Requested setting: ").append(desiredAutoCommit).append(". Cause: ").append(e).toString(), e);
- }
- }
-
- protected void resetAutoCommit()
- {
- try
- {
- if(!connection.getAutoCommit())
- {
- if(log.isDebugEnabled())
- log.debug((new StringBuilder()).append("Resetting autocommit to true on JDBC Connection [").append(connection).append("]").toString());
- connection.setAutoCommit(true);
- }
- }
- catch(SQLException e)
- {
- log.debug((new StringBuilder()).append("Error resetting autocommit to true before closing the connection. Cause: ").append(e).toString());
- }
- }
- //獲取connection
- protected void openConnection()
- throws SQLException
- {
- if(log.isDebugEnabled())
- log.debug("Openning JDBC Connection");
- connection = dataSource.getConnection();
- if(level != null)
- connection.setTransactionIsolation(level.getLevel());
- setDesiredAutoCommit(autoCommmit);
- }
- }
//Transaction
Java代碼
- public interface Transaction
- {
-
- public abstract Connection getConnection()
- throws SQLException;
-
- public abstract void commit()
- throws SQLException;
-
- public abstract void rollback()
- throws SQLException;
-
- public abstract void close()
- throws SQLException;
- }
從上面能夠看出jdbc對應的事務工廠爲JdbcTransactionFactory,由JdbcTransactionFactory,根據數據源,事務級別以及自動提交屬性來,建立JdbcTransaction,而JdbcTransaction的事務管理,是經過數據鏈接connection,而connection是從datasource獲取,JdbcTransaction的事務管理,就是依靠相應的數據庫driver,來管理,實際依賴於數據庫。 下載
//解析dataSource
Java代碼
- private DataSourceFactory dataSourceElement(XNode context)
- throws Exception
- {
- if(context != null)
- {
- //獲取數據源的類型,和屬性
- String type = context.getStringAttribute("type");
- Properties props = context.getChildrenAsProperties();
- //根據type從configuration的類型處理器,獲取具體的DataSourceFactory
- //從上文,咱們看一看到type爲POOLED,對應的是PooledDataSourceFactory
- DataSourceFactory factory = (DataSourceFactory)resolveClass(type).newInstance();
- factory.setProperties(props);
- return factory;
- } else
- {
- throw new BuilderException("Environment declaration requires a DataSourceFactory.");
- }
- }
// PooledDataSourceFactory
Java代碼
- public class PooledDataSourceFactory extends UnpooledDataSourceFactory
- {
-
- public PooledDataSourceFactory()
- {
- dataSource = new PooledDataSource();
- }
- }