public void Set_Int32() { var obj = new AllPrimitive { }; ISetAccessorFactory setAccessorFactory = EmitSetAccessorFactory.Instance; var set_Int32 = setAccessorFactory.Create(typeof(AllPrimitive), nameof(AllPrimitive.Int32)); set_Int32(obj, 1); Assert.Equal(1, obj.Int32); }
/// <summary> /// Sets the member. /// </summary> /// <param name="obj">The obj.</param> /// <param name="memberName">Name of the member.</param> /// <param name="memberValue">The member value.</param> /// <param name="accessorFactory">The accessor factory.</param> public static void SetMember(object obj, string memberName, object memberValue, AccessorFactory accessorFactory) { try { if (memberName.IndexOf("[") > -1) { SetArrayMember(obj, memberName, memberValue, accessorFactory); } else { if (obj is IDictionary) { ((IDictionary)obj)[memberName] = memberValue; } else if (obj is IDictionary <string, object> ) { ((IDictionary <string, object>)obj)[memberName] = memberValue; } else { Type targetType = obj.GetType(); ISetAccessorFactory setAccessorFactory = accessorFactory.SetAccessorFactory; ISetAccessor setAccessor = setAccessorFactory.CreateSetAccessor(targetType, memberName); if (setAccessor == null) { throw new ProbeException("No Set method for member " + memberName + " on instance of " + obj.GetType().Name); } try { setAccessorFactory.CreateSetAccessor(targetType, memberName).Set(obj, memberValue); } catch (Exception ex) { throw new ProbeException(ex); } } } } catch (ProbeException) { throw; } catch (Exception e) { throw new ProbeException("Could not Get property '" + memberName + "' for " + obj.GetType().Name + ". Cause: " + e.Message, e); } }
/// <summary> /// Sets the value to the parameter property. /// </summary> /// <remarks>Use to set value on output parameter</remarks> /// <param name="mapping"></param> /// <param name="target"></param> /// <param name="dataBaseValue"></param> public override void SetData(ref object target, ParameterProperty mapping, object dataBaseValue) { if (mapping.IsComplexMemberName) { ObjectProbe.SetMemberValue(target, mapping.PropertyName, dataBaseValue, this.DataExchangeFactory.ObjectFactory, this.DataExchangeFactory.AccessorFactory); } else { ISetAccessorFactory setAccessorFactory = this.DataExchangeFactory.AccessorFactory.SetAccessorFactory; ISetAccessor _setAccessor = setAccessorFactory.CreateSetAccessor(_parameterClass, mapping.PropertyName); _setAccessor.Set(target, dataBaseValue); } }
/// <summary> /// Builds the the MyBatis core model (statement, alias, resultMap, parameterMap, dataSource) /// from an <see cref="IConfigurationStore"/> and store all the refrences in an <see cref="IModelStore"/> . /// </summary> /// <param name="configurationSetting">The configuration setting.</param> /// <param name="store">The configuration store.</param> /// <returns>The model store</returns> public virtual void BuildModel(ConfigurationSetting configurationSetting, IConfigurationStore store) { IObjectFactory objectFactory = null; IGetAccessorFactory getAccessorFactory = null; ISetAccessorFactory setAccessorFactory = null; ISessionFactory sessionFactory = null; ISessionStore sessionStore = null; if (configurationSetting != null) { objectFactory = configurationSetting.ObjectFactory; setAccessorFactory = configurationSetting.SetAccessorFactory; getAccessorFactory = configurationSetting.GetAccessorFactory; dataSource = configurationSetting.DataSource; sessionFactory = configurationSetting.SessionFactory; sessionStore = configurationSetting.SessionStore; dynamicSqlEngine = configurationSetting.DynamicSqlEngine; isCacheModelsEnabled = configurationSetting.IsCacheModelsEnabled; useStatementNamespaces = configurationSetting.UseStatementNamespaces; useReflectionOptimizer = configurationSetting.UseReflectionOptimizer; preserveWhitespace = configurationSetting.PreserveWhitespace; } // Xml setting override code setting LoadSetting(store); if (objectFactory == null) { objectFactory = new ObjectFactory(useReflectionOptimizer); } if (setAccessorFactory == null) { setAccessorFactory = new SetAccessorFactory(useReflectionOptimizer); } if (getAccessorFactory == null) { getAccessorFactory = new GetAccessorFactory(useReflectionOptimizer); } AccessorFactory accessorFactory = new AccessorFactory(setAccessorFactory, getAccessorFactory); TypeHandlerFactory typeHandlerFactory = new TypeHandlerFactory(); TypeAlias alias = new TypeAlias("MEMORY", typeof(PerpetualCache)); typeHandlerFactory.AddTypeAlias(alias.Id, alias); alias = new TypeAlias("Perpetual", typeof(PerpetualCache)); typeHandlerFactory.AddTypeAlias(alias.Id, alias); alias = new TypeAlias("LRU", typeof(LruCache)); typeHandlerFactory.AddTypeAlias(alias.Id, alias); alias = new TypeAlias("Lru", typeof(LruCache)); typeHandlerFactory.AddTypeAlias(alias.Id, alias); alias = new TypeAlias("FIFO", typeof(FifoCache)); typeHandlerFactory.AddTypeAlias(alias.Id, alias); alias = new TypeAlias("Fifo", typeof(FifoCache)); typeHandlerFactory.AddTypeAlias(alias.Id, alias); alias = new TypeAlias("Weak", typeof(WeakCache)); typeHandlerFactory.AddTypeAlias(alias.Id, alias); alias = new TypeAlias("WEAK", typeof(WeakCache)); typeHandlerFactory.AddTypeAlias(alias.Id, alias); alias = new TypeAlias("AnsiStringTypeHandler", typeof(AnsiStringTypeHandler)); typeHandlerFactory.AddTypeAlias(alias.Id, alias); modelStore.DataExchangeFactory = new DataExchangeFactory(typeHandlerFactory, objectFactory, accessorFactory); if (sessionStore == null) { sessionStore = SessionStoreFactory.GetSessionStore(modelStore.Id); } modelStore.SessionStore = sessionStore; deSerializerFactory = new DeSerializerFactory(modelStore); ParameterMap emptyParameterMap = new ParameterMap( ConfigConstants.EMPTY_PARAMETER_MAP, string.Empty, string.Empty, typeof(string), modelStore.DataExchangeFactory.GetDataExchangeForClass(null), false); modelStore.AddParameterMap(emptyParameterMap); BuildProviders(store); BuildDataSource(store); if (sessionFactory == null) { sessionFactory = new DefaultSessionFactory( dataSource, modelStore.SessionStore, new DefaultTransactionManager(new AdoTransactionFactory())); } modelStore.SessionFactory = sessionFactory; BuildTypeAlias(store); BuildTypeHandlers(store); BuildCacheModels(store); BuildResultMaps(store); for (int i = 0; i < nestedProperties.Count; i++) { ResultProperty property = nestedProperties[i]; property.NestedResultMap = modelStore.GetResultMap(property.NestedResultMapName); } for (int i = 0; i < discriminators.Count; i++) { discriminators[i].Initialize(modelStore); } BuildParameterMaps(store); BuildMappedStatements(store, configurationSetting); for (int i = 0; i < store.CacheModels.Length; i++) { CacheModel cacheModel = modelStore.GetCacheModel(store.CacheModels[i].Id); for (int j = 0; j < cacheModel.StatementFlushNames.Count; j++) { string statement = cacheModel.StatementFlushNames[j]; IMappedStatement mappedStatement = modelStore.GetMappedStatement(statement); if (mappedStatement != null) { cacheModel.RegisterTriggerStatement(mappedStatement); if (logger.IsDebugEnabled) { logger.Debug("Registering trigger statement [" + statement + "] to cache model [" + cacheModel.Id + "]"); } } else { if (logger.IsWarnEnabled) { logger.Warn("Unable to register trigger statement [" + statement + "] to cache model [" + cacheModel.Id + "]. Statement does not exist."); } } } } if (logger.IsInfoEnabled) { logger.Info("Model Store"); logger.Info(modelStore.ToString()); } }
/// <summary> /// Initializes a new instance of the <see cref="AccessorFactory"/> class. /// </summary> /// <param name="setAccessorFactory">The set accessor factory.</param> /// <param name="getAccessorFactory">The get accessor factory.</param> public AccessorFactory(ISetAccessorFactory setAccessorFactory, IGetAccessorFactory getAccessorFactory) { _setAccessorFactory = setAccessorFactory; _getAccessorFactory = getAccessorFactory; }
/// <summary> /// Builds a <see cref="ResultPropertyCollection"/> for an <see cref="AutoResultMap"/>. /// </summary> /// <param name="dataExchangeFactory">The data exchange factory.</param> /// <param name="reader">The reader.</param> /// <param name="resultObject">The result object.</param> public static ResultPropertyCollection Build(DataExchangeFactory dataExchangeFactory, IDataReader reader, ref object resultObject) { Type targetType = resultObject.GetType(); ResultPropertyCollection properties = new ResultPropertyCollection(); try { // Get all PropertyInfo from the resultObject properties ReflectionInfo reflectionInfo = ReflectionInfo.GetInstance(targetType); string[] membersName = reflectionInfo.GetWriteableMemberNames(); IDictionary <string, ISetAccessor> propertyMap = new Dictionary <string, ISetAccessor>(); int length = membersName.Length; for (int i = 0; i < length; i++) { ISetAccessorFactory setAccessorFactory = dataExchangeFactory.AccessorFactory.SetAccessorFactory; ISetAccessor setAccessor = setAccessorFactory.CreateSetAccessor(targetType, membersName[i]); propertyMap.Add(membersName[i], setAccessor); } // Get all column Name from the reader // and build a resultMap from with the help of the PropertyInfo[]. DataTable dataColumn = reader.GetSchemaTable(); int count = dataColumn.Rows.Count; for (int i = 0; i < count; i++) { string propertyName = string.Empty; string columnName = dataColumn.Rows[i][0].ToString(); ISetAccessor matchedSetAccessor = null; propertyMap.TryGetValue(columnName, out matchedSetAccessor); int columnIndex = i; if (resultObject is Hashtable) { propertyName = columnName; ResultProperty property = new ResultProperty( propertyName, columnName, columnIndex, string.Empty, string.Empty, string.Empty, false, string.Empty, null, string.Empty, targetType, dataExchangeFactory, null); properties.Add(property); } Type propertyType = null; if (matchedSetAccessor == null) { try { propertyType = ObjectProbe.GetMemberTypeForSetter(resultObject, columnName); } catch { _logger.Error("The column [" + columnName + "] could not be auto mapped to a property on [" + resultObject + "]"); } } else { propertyType = matchedSetAccessor.MemberType; } if (propertyType != null || matchedSetAccessor != null) { propertyName = (matchedSetAccessor != null ? matchedSetAccessor.Name : columnName); ITypeHandler typeHandler = null; if (matchedSetAccessor != null) { //property.Initialize(dataExchangeFactory.TypeHandlerFactory, matchedSetAccessor); typeHandler = dataExchangeFactory.TypeHandlerFactory.GetTypeHandler(matchedSetAccessor.MemberType); } else { typeHandler = dataExchangeFactory.TypeHandlerFactory.GetTypeHandler(propertyType); } //property.PropertyStrategy = PropertyStrategyFactory.Get(property); ResultProperty property = new ResultProperty( propertyName, columnName, columnIndex, string.Empty, string.Empty, string.Empty, false, string.Empty, null, string.Empty, targetType, dataExchangeFactory, typeHandler); properties.Add(property); } } } catch (Exception e) { throw new DataMapperException("Error automapping columns. Cause: " + e.Message, e); } return(properties); }
public MultipleResultDeserializer(IDeserializerFactory deserializerFactory) { _deserializerFactory = deserializerFactory; _setAccessorFactory = new EmitSetAccessorFactory(); }
/// <summary> /// Builds a <see cref="ResultPropertyCollection"/> for an <see cref="AutoResultMap"/>. /// </summary> /// <param name="dataExchangeFactory">The data exchange factory.</param> /// <param name="reader">The reader.</param> /// <param name="resultObject">The result object.</param> public static ResultPropertyCollection Build <T>(DataExchangeFactory dataExchangeFactory, IDataReader reader, ref T resultObject) { Type targetType = resultObject.GetType(); ResultPropertyCollection properties = new ResultPropertyCollection(); try { // Get all PropertyInfo from the resultObject properties var reflectionInfo = ReflectionInfo.GetInstance(targetType); var membersName = reflectionInfo.GetWriteableMemberNames(); var propertyMap = new Hashtable(); int length = membersName.Length; for (int i = 0; i < length; i++) { ISetAccessorFactory setAccessorFactory = dataExchangeFactory.AccessorFactory.SetAccessorFactory; ISetAccessor setAccessor = setAccessorFactory.CreateSetAccessor(targetType, membersName[i]); propertyMap.Add(membersName[i], setAccessor); } // Get all column Name from the reader // and build a resultMap from with the help of the PropertyInfo[]. var dataColumn = reader.GetSchemaTable(); if (dataColumn == null) { return(new ResultPropertyCollection()); } int count = dataColumn.Rows.Count; for (int i = 0; i < count; i++) { var columnName = dataColumn.Rows[i][0].ToString(); var matchedSetAccessor = propertyMap[columnName] as ISetAccessor; var property = new ResultProperty { ColumnName = columnName, ColumnIndex = i }; if (resultObject is Hashtable) { property.PropertyName = columnName; properties.Add(property); } Type propertyType = null; if (matchedSetAccessor == null) { try { propertyType = ObjectProbe.GetMemberTypeForSetter(resultObject, columnName); } catch { // ignored } } else { propertyType = matchedSetAccessor.MemberType; } if (propertyType != null || matchedSetAccessor != null) { property.PropertyName = (matchedSetAccessor != null ? matchedSetAccessor.Name : columnName); if (matchedSetAccessor != null) { property.Initialize(dataExchangeFactory.TypeHandlerFactory, matchedSetAccessor); } else { property.TypeHandler = dataExchangeFactory.TypeHandlerFactory.GetTypeHandler(propertyType); } property.PropertyStrategy = PropertyStrategyFactory.Get(property); properties.Add(property); } } } catch (Exception e) { throw new DataMapperException("Error automapping columns. Cause: " + e.Message, e); } return(properties); }
protected virtual void TearDownFixture() { factoryGet = null; factorySet = null; }
protected virtual void SetUpFixture() { factoryGet = new GetAccessorFactory(true); factorySet = new SetAccessorFactory(true); }
public MultipleResultDeserializer(IDeserializerFactory deserializerFactory) { _deserializerFactory = deserializerFactory; _setAccessorFactory = EmitSetAccessorFactory.Instance; }
/// <summary> /// Intialize the internal ISqlMapper instance. /// </summary> private void Initialize() { Reset(); #region Load Global Properties if (_configScope.IsCallFromDao == false) { _configScope.NodeContext = _configScope.SqlMapConfigDocument.SelectSingleNode( ApplyDataMapperNamespacePrefix(XML_DATAMAPPER_CONFIG_ROOT), _configScope.XmlNamespaceManager); ParseGlobalProperties(); } #endregion #region Load settings _configScope.ErrorContext.Activity = "loading global settings"; XmlNodeList settings = _configScope.SqlMapConfigDocument.SelectNodes( ApplyDataMapperNamespacePrefix(XML_CONFIG_SETTINGS), _configScope.XmlNamespaceManager); if (settings!=null) { foreach (XmlNode setting in settings) { if (setting.Attributes[ATR_USE_STATEMENT_NAMESPACES] != null ) { string value = NodeUtils.ParsePropertyTokens(setting.Attributes[ATR_USE_STATEMENT_NAMESPACES].Value, _configScope.Properties); _configScope.UseStatementNamespaces = Convert.ToBoolean( value ); } if (setting.Attributes[ATR_CACHE_MODELS_ENABLED] != null ) { string value = NodeUtils.ParsePropertyTokens(setting.Attributes[ATR_CACHE_MODELS_ENABLED].Value, _configScope.Properties); _configScope.IsCacheModelsEnabled = Convert.ToBoolean( value ); } if (setting.Attributes[ATR_USE_REFLECTION_OPTIMIZER] != null ) { string value = NodeUtils.ParsePropertyTokens(setting.Attributes[ATR_USE_REFLECTION_OPTIMIZER].Value, _configScope.Properties); _configScope.UseReflectionOptimizer = Convert.ToBoolean( value ); } if (setting.Attributes[ATR_VALIDATE_SQLMAP] != null ) { string value = NodeUtils.ParsePropertyTokens(setting.Attributes[ATR_VALIDATE_SQLMAP].Value, _configScope.Properties); _configScope.ValidateSqlMap = Convert.ToBoolean( value ); } } } #endregion if (_objectFactory == null) { _objectFactory = new ObjectFactory(_configScope.UseReflectionOptimizer); } if (_setAccessorFactory == null) { _setAccessorFactory = new SetAccessorFactory(_configScope.UseReflectionOptimizer); } if (_getAccessorFactory == null) { _getAccessorFactory = new GetAccessorFactory(_configScope.UseReflectionOptimizer); } if (_sqlMapper == null) { AccessorFactory accessorFactory = new AccessorFactory(_setAccessorFactory, _getAccessorFactory); _configScope.SqlMapper = new SqlMapper(_objectFactory, accessorFactory); } else { _configScope.SqlMapper = _sqlMapper; } ParameterMap emptyParameterMap = new ParameterMap(_configScope.DataExchangeFactory); emptyParameterMap.Id = ConfigurationScope.EMPTY_PARAMETER_MAP; _configScope.SqlMapper.AddParameterMap( emptyParameterMap ); _configScope.SqlMapper.IsCacheModelsEnabled = _configScope.IsCacheModelsEnabled; #region Cache Alias TypeAlias cacheAlias = new TypeAlias(typeof(MemoryCacheControler)); cacheAlias.Name = "MEMORY"; _configScope.SqlMapper.TypeHandlerFactory.AddTypeAlias(cacheAlias.Name, cacheAlias); cacheAlias = new TypeAlias(typeof(LruCacheController)); cacheAlias.Name = "LRU"; _configScope.SqlMapper.TypeHandlerFactory.AddTypeAlias(cacheAlias.Name, cacheAlias); cacheAlias = new TypeAlias(typeof(FifoCacheController)); cacheAlias.Name = "FIFO"; _configScope.SqlMapper.TypeHandlerFactory.AddTypeAlias(cacheAlias.Name, cacheAlias); cacheAlias = new TypeAlias(typeof(AnsiStringTypeHandler)); cacheAlias.Name = "AnsiStringTypeHandler"; _configScope.SqlMapper.TypeHandlerFactory.AddTypeAlias(cacheAlias.Name, cacheAlias); #endregion #region Load providers if (_configScope.IsCallFromDao == false) { GetProviders(); } #endregion #region Load DataBase #region Choose the provider IDbProvider provider = null; if ( _configScope.IsCallFromDao==false ) { provider = ParseProvider(); _configScope.ErrorContext.Reset(); } #endregion #region Load the DataSources _configScope.ErrorContext.Activity = "loading Database DataSource"; XmlNode nodeDataSource = _configScope.SqlMapConfigDocument.SelectSingleNode( ApplyDataMapperNamespacePrefix(XML_DATABASE_DATASOURCE), _configScope.XmlNamespaceManager ); if (nodeDataSource == null) { if (_configScope.IsCallFromDao == false) { throw new ConfigurationException("There's no dataSource tag in SqlMap.config."); } else // patch from Luke Yang { _configScope.SqlMapper.DataSource = _configScope.DataSource; } } else { if (_configScope.IsCallFromDao == false) { _configScope.ErrorContext.Resource = nodeDataSource.OuterXml.ToString(); _configScope.ErrorContext.MoreInfo = "parse DataSource"; DataSource dataSource = DataSourceDeSerializer.Deserialize( nodeDataSource ); dataSource.DbProvider = provider; dataSource.ConnectionString = NodeUtils.ParsePropertyTokens(dataSource.ConnectionString, _configScope.Properties); _configScope.DataSource = dataSource; _configScope.SqlMapper.DataSource = _configScope.DataSource; } else { _configScope.SqlMapper.DataSource = _configScope.DataSource; } _configScope.ErrorContext.Reset(); } #endregion #endregion #region Load Global TypeAlias foreach (XmlNode xmlNode in _configScope.SqlMapConfigDocument.SelectNodes( ApplyDataMapperNamespacePrefix(XML_GLOBAL_TYPEALIAS), _configScope.XmlNamespaceManager)) { _configScope.ErrorContext.Activity = "loading global Type alias"; TypeAliasDeSerializer.Deserialize(xmlNode, _configScope); } _configScope.ErrorContext.Reset(); #endregion #region Load TypeHandlers foreach (XmlNode xmlNode in _configScope.SqlMapConfigDocument.SelectNodes( ApplyDataMapperNamespacePrefix(XML_GLOBAL_TYPEHANDLER), _configScope.XmlNamespaceManager)) { try { _configScope.ErrorContext.Activity = "loading typeHandler"; TypeHandlerDeSerializer.Deserialize( xmlNode, _configScope ); } catch (Exception e) { NameValueCollection prop = NodeUtils.ParseAttributes(xmlNode, _configScope.Properties); throw new ConfigurationException( String.Format("Error registering TypeHandler class \"{0}\" for handling .Net type \"{1}\" and dbType \"{2}\". Cause: {3}", NodeUtils.GetStringAttribute(prop, "callback"), NodeUtils.GetStringAttribute(prop, "type"), NodeUtils.GetStringAttribute(prop, "dbType"), e.Message), e); } } _configScope.ErrorContext.Reset(); #endregion #region Load sqlMap mapping files foreach (XmlNode xmlNode in _configScope.SqlMapConfigDocument.SelectNodes( ApplyDataMapperNamespacePrefix(XML_SQLMAP), _configScope.XmlNamespaceManager)) { _configScope.NodeContext = xmlNode; ConfigureSqlMap(); } #endregion #region Attach CacheModel to statement if (_configScope.IsCacheModelsEnabled) { foreach(DictionaryEntry entry in _configScope.SqlMapper.MappedStatements) { _configScope.ErrorContext.Activity = "Set CacheModel to statement"; IMappedStatement mappedStatement = (IMappedStatement)entry.Value; if (mappedStatement.Statement.CacheModelName.Length >0) { _configScope.ErrorContext.MoreInfo = "statement : "+mappedStatement.Statement.Id; _configScope.ErrorContext.Resource = "cacheModel : " +mappedStatement.Statement.CacheModelName; mappedStatement.Statement.CacheModel = _configScope.SqlMapper.GetCache(mappedStatement.Statement.CacheModelName); } } } _configScope.ErrorContext.Reset(); #endregion #region Register Trigger Statements for Cache Models foreach (DictionaryEntry entry in _configScope.CacheModelFlushOnExecuteStatements) { string cacheModelId = (string)entry.Key; IList statementsToRegister = (IList)entry.Value; if (statementsToRegister != null && statementsToRegister.Count > 0) { foreach (string statementName in statementsToRegister) { IMappedStatement mappedStatement = _configScope.SqlMapper.MappedStatements[statementName] as IMappedStatement; if (mappedStatement != null) { CacheModel cacheModel = _configScope.SqlMapper.GetCache(cacheModelId); if (_logger.IsDebugEnabled) { _logger.Debug("Registering trigger statement [" + mappedStatement.Id + "] to cache model [" + cacheModel.Id + "]"); } cacheModel.RegisterTriggerStatement(mappedStatement); } else { if (_logger.IsWarnEnabled) { _logger.Warn("Unable to register trigger statement [" + statementName + "] to cache model [" + cacheModelId + "]. Statement does not exist."); } } } } } #endregion #region Resolve resultMap / Discriminator / PropertyStategy attributes on Result/Argument Property foreach(DictionaryEntry entry in _configScope.SqlMapper.ResultMaps) { _configScope.ErrorContext.Activity = "Resolve 'resultMap' attribute on Result Property"; ResultMap resultMap = (ResultMap)entry.Value; for(int index=0; index< resultMap.Properties.Count; index++) { ResultProperty result = resultMap.Properties[index]; if(result.NestedResultMapName.Length >0) { result.NestedResultMap = _configScope.SqlMapper.GetResultMap(result.NestedResultMapName); } result.PropertyStrategy = PropertyStrategyFactory.Get(result); } for(int index=0; index< resultMap.Parameters.Count; index++) { ResultProperty result = resultMap.Parameters[index]; if(result.NestedResultMapName.Length >0) { result.NestedResultMap = _configScope.SqlMapper.GetResultMap(result.NestedResultMapName); } result.ArgumentStrategy = ArgumentStrategyFactory.Get( (ArgumentProperty)result ); } if (resultMap.Discriminator != null) { resultMap.Discriminator.Initialize(_configScope); } } _configScope.ErrorContext.Reset(); #endregion }
public AccessorFactory(ISetAccessorFactory setAccessorFactory, IGetAccessorFactory getAccessorFactory) { this._setAccessorFactory = setAccessorFactory; this._getAccessorFactory = getAccessorFactory; }
/// <summary> /// Builds the the iBATIS core model (statement, alias, resultMap, parameterMap, dataSource) /// from an <see cref="IConfigurationStore"/> and store all the refrences in an <see cref="IModelStore"/> . /// </summary> /// <param name="configurationSetting">The configuration setting.</param> /// <param name="store">The configuration store.</param> /// <returns>The model store</returns> public virtual void BuildModel(ConfigurationSetting configurationSetting, IConfigurationStore store) { IObjectFactory objectFactory = null; IGetAccessorFactory getAccessorFactory = null; ISetAccessorFactory setAccessorFactory = null; ISessionFactory sessionFactory = null; ISessionStore sessionStore = null; if (configurationSetting != null) { objectFactory = configurationSetting.ObjectFactory; setAccessorFactory = configurationSetting.SetAccessorFactory; getAccessorFactory = configurationSetting.GetAccessorFactory; dataSource = configurationSetting.DataSource; sessionFactory = configurationSetting.SessionFactory; sessionStore = configurationSetting.SessionStore; dynamicSqlEngine = configurationSetting.DynamicSqlEngine; isCacheModelsEnabled = configurationSetting.IsCacheModelsEnabled; useStatementNamespaces = configurationSetting.UseStatementNamespaces; useReflectionOptimizer = configurationSetting.UseReflectionOptimizer; preserveWhitespace = configurationSetting.PreserveWhitespace; } // Xml setting override code setting //取store中的数据初始化类成员 为下面做准备 LoadSetting(store); if (objectFactory == null) { objectFactory = new ObjectFactory(useReflectionOptimizer); } if (setAccessorFactory == null) { setAccessorFactory = new SetAccessorFactory(useReflectionOptimizer); } if (getAccessorFactory == null) { getAccessorFactory = new GetAccessorFactory(useReflectionOptimizer); } AccessorFactory accessorFactory = new AccessorFactory(setAccessorFactory, getAccessorFactory); TypeHandlerFactory typeHandlerFactory = new TypeHandlerFactory(); TypeAlias alias = new TypeAlias("MEMORY", typeof(PerpetualCache)); typeHandlerFactory.AddTypeAlias(alias.Id, alias); alias = new TypeAlias("Perpetual", typeof(PerpetualCache)); typeHandlerFactory.AddTypeAlias(alias.Id, alias); alias = new TypeAlias("LRU", typeof(LruCache)); typeHandlerFactory.AddTypeAlias(alias.Id, alias); alias = new TypeAlias("Lru", typeof(LruCache)); typeHandlerFactory.AddTypeAlias(alias.Id, alias); alias = new TypeAlias("FIFO", typeof(FifoCache)); typeHandlerFactory.AddTypeAlias(alias.Id, alias); alias = new TypeAlias("Fifo", typeof(FifoCache)); typeHandlerFactory.AddTypeAlias(alias.Id, alias); alias = new TypeAlias("Weak", typeof(WeakCache)); typeHandlerFactory.AddTypeAlias(alias.Id, alias); alias = new TypeAlias("WEAK", typeof(WeakCache)); typeHandlerFactory.AddTypeAlias(alias.Id, alias); alias = new TypeAlias("MemCached", typeof(MemCached)); typeHandlerFactory.AddTypeAlias(alias.Id, alias); alias = new TypeAlias("MEMCACHED", typeof(MemCached)); typeHandlerFactory.AddTypeAlias(alias.Id, alias); alias = new TypeAlias("AnsiStringTypeHandler", typeof(AnsiStringTypeHandler)); typeHandlerFactory.AddTypeAlias(alias.Id, alias); //将以上类信息存入到modelStore中 实质性工作 modelStore.DataExchangeFactory = new DataExchangeFactory(typeHandlerFactory, objectFactory, accessorFactory); if (sessionStore == null) { sessionStore = SessionStoreFactory.GetSessionStore(modelStore.Id); } //将ISessionStore类对象存入modelStore中 准备数据库的连接 与 事物操作功能 实质性工作 modelStore.SessionStore = sessionStore; //初始化DefaultModelBuilder的成员变量 deSerializerFactory = new DeSerializerFactory(modelStore); //设置一个空类型的参数映射类 ParameterMap emptyParameterMap = new ParameterMap( ConfigConstants.EMPTY_PARAMETER_MAP, string.Empty, string.Empty, typeof(string), modelStore.DataExchangeFactory.GetDataExchangeForClass(null), //获得ComplexDataExchange对象 false); //向参数字典中添加一个空参数类 modelStore.AddParameterMap(emptyParameterMap); //完成了对DefaultModelBuilder成员变量dbProviderFactory的初始化,其中完成了对provider使用中节点的类初始化 BuildProviders(store); //完成了对DefaultModelBuilder成员变量IDataSource的初始化,包括数据库的名字 连接字符串 以及DbPrivder类 BuildDataSource(store); if (sessionFactory == null) { sessionFactory = new DefaultSessionFactory( dataSource, modelStore.SessionStore, new DefaultTransactionManager(new AdoTransactionFactory())); } //初始化modelStore中的ISessionFactory变量 modelStore.SessionFactory = sessionFactory; //将具体SQLXML配置文件中的Alias节点对应的别名信息写入到modelStore中的TypeHandlerFactory的字典中 BuildTypeAlias(store); //将TypeHanders下的子节点信息放入 modelStore.DataExchangeFactory.TypeHandlerFactory中的字典当中 BuildTypeHandlers(store); //将cacheModels下子节点cacheModel加入到modelStore的CacheModel字典中 BuildCacheModels(store); //将resultMap节点信息添加到modelStore的resultMaps中 BuildResultMaps(store); //为resultMapping属性所在的节点信息类设置对应的ResultProperty for (int i = 0; i < nestedProperties.Count; i++) { ResultProperty property = nestedProperties[i]; property.NestedResultMap = modelStore.GetResultMap(property.NestedResultMapName); } for (int i = 0; i < discriminators.Count; i++) { //完成对discriminator类中对字典的初始化 discriminators[i].Initialize(modelStore); } //将parameter节点信息添加到modelStore类中的parameterMaps字典中 BuildParameterMaps(store); //将statements下的节点添加到modelStore的statements的字典中 BuildMappedStatements(store, configurationSetting); for (int i = 0; i < store.CacheModels.Length; i++) { CacheModel cacheModel = modelStore.GetCacheModel(store.CacheModels[i].Id); for (int j = 0; j < cacheModel.StatementFlushNames.Count; j++) { string statement = cacheModel.StatementFlushNames[j]; IMappedStatement mappedStatement = modelStore.GetMappedStatement(statement); if (mappedStatement != null) { //为IMappedStatement类的Executed制定委托事件 目的是清空缓存 cacheModel.RegisterTriggerStatement(mappedStatement); if (logger.IsDebugEnabled) { logger.Debug("Registering trigger statement [" + statement + "] to cache model [" + cacheModel.Id + "]"); } } else { if (logger.IsWarnEnabled) { logger.Warn("Unable to register trigger statement [" + statement + "] to cache model [" + cacheModel.Id + "]. Statement does not exist."); } } } } if (logger.IsInfoEnabled) { logger.Info("Model Store"); logger.Info(modelStore.ToString()); } }
/// <summary> /// Builds a <see cref="ResultPropertyCollection"/> for an <see cref="AutoResultMap"/>. /// </summary> /// <param name="dataExchangeFactory">The data exchange factory.</param> /// <param name="reader">The reader.</param> /// <param name="resultObject">The result object.</param> /// <param name="isUseAutoMapCompatibilityMode">The result object.</param> public static ResultPropertyCollection Build(DataExchangeFactory dataExchangeFactory, IDataReader reader, ref object resultObject, bool isUseAutoMapCompatibilityMode) { Type targetType = resultObject.GetType(); ResultPropertyCollection properties = new ResultPropertyCollection(); try { // Get all PropertyInfo from the resultObject properties ReflectionInfo reflectionInfo = ReflectionInfo.GetInstance(targetType); string[] membersName = reflectionInfo.GetPublicWriteableMemberNames(); Hashtable propertyMap = new Hashtable(); int length = membersName.Length; for (int i = 0; i < length; i++) { var memberName = membersName[i]; ISetAccessorFactory setAccessorFactory = dataExchangeFactory.AccessorFactory.SetAccessorFactory; ISetAccessor setAccessor = setAccessorFactory.CreateSetAccessor(targetType, memberName); var menberInfo = reflectionInfo.GetSetter(memberName); //ʹ�ñ�ע������Ϊ�к����ԵĹ�ϵ var attrs = menberInfo.GetCustomAttribute <AliasAttribute>(); if (attrs != null) { memberName = attrs.Name; } else if (isUseAutoMapCompatibilityMode)//���ü���ģʽ { memberName = memberName.Replace("_", "").ToLower(); } propertyMap.Add(memberName, setAccessor); } // Get all column Name from the reader // and build a resultMap from with the help of the PropertyInfo[]. DataTable dataColumn = reader.GetSchemaTable(); int count = dataColumn.Rows.Count; for (int i = 0; i < count; i++) { string columnName = dataColumn.Rows[i][0].ToString(); ISetAccessor matchedSetAccessor = propertyMap[columnName] as ISetAccessor; if (matchedSetAccessor == null && isUseAutoMapCompatibilityMode) { columnName = columnName.Replace("_", "").ToLower(); matchedSetAccessor = propertyMap[columnName] as ISetAccessor; } ResultProperty property = new ResultProperty(); property.ColumnName = columnName; property.ColumnIndex = i; if (resultObject is Hashtable) { property.PropertyName = columnName; properties.Add(property); } Type propertyType = null; if (matchedSetAccessor == null) { try { propertyType = ObjectProbe.GetMemberTypeForSetter(resultObject, columnName); } catch { _logger.Error("The column [" + columnName + "] could not be auto mapped to a property on [" + resultObject.ToString() + "]"); } } else { propertyType = matchedSetAccessor.MemberType; } if (propertyType != null || matchedSetAccessor != null) { property.PropertyName = (matchedSetAccessor != null ? matchedSetAccessor.Name : columnName); if (matchedSetAccessor != null) { property.Initialize(dataExchangeFactory.TypeHandlerFactory, matchedSetAccessor); } else { property.TypeHandler = dataExchangeFactory.TypeHandlerFactory.GetTypeHandler(propertyType); } property.PropertyStrategy = PropertyStrategyFactory.Get(property); properties.Add(property); } } } catch (Exception e) { throw new DataMapperException("Error automapping columns. Cause: " + e.Message, e); } return(properties); }