示例#1
0
        /// <summary>
        /// Builds an <see cref="Delete"/> for a delete configuration.
        /// </summary>
        /// <param name="statementConfig">The statement config.</param>
        /// <param name="configurationSetting"></param>
        private IMappedStatement BuildDelete(IConfiguration statementConfig, ConfigurationSetting configurationSetting)
        {
            BaseStatementDeSerializer deleteDeSerializer = new DeleteDeSerializer();
            IStatement statement = deleteDeSerializer.Deserialize(modelStore, statementConfig, configurationSetting);
            ProcessSqlStatement(statementConfig, statement);
            MappedStatement mappedStatement = new DeleteMappedStatement(modelStore, statement);

            return BuildCachingStatement(statement, mappedStatement);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="DefaultConfigurationEngine"/> class.
        /// </summary>
        public DefaultConfigurationEngine()
        {
            configurationStore = new DefaultConfigurationStore();
            configurationSetting = new ConfigurationSetting();
            modules = new List<IModule>();

            ResourceLoaderRegistry.ResetEventHandler();
            ResourceLoaderRegistry.LoadFileResource += FileResourceEventHandler;
        }
        public void ConfigurationStore_should_contain_module_configuration()
        {
            ConfigurationSetting configurationSetting = new ConfigurationSetting();
            configurationSetting.DataSource = new FakeDataSource();

            IConfigurationEngine engine = new DefaultConfigurationEngine(configurationSetting);
            engine.RegisterModule(new MyModule());

            engine.BuildMapperFactory();

            CheckConfigurationStore(engine.ConfigurationStore);
        }
示例#4
0
        public void SetUpFixture()
        {
            string uri = "file://~/SqlMap.event.config";
            IResource resource = ResourceLoaderRegistry.GetResource(uri);

            ConfigurationSetting setting = new ConfigurationSetting();
            IConfigurationEngine engine = new DefaultConfigurationEngine(setting);
            engine.RegisterInterpreter(new XmlConfigurationInterpreter(resource));
            engine.RegisterModule(new EventModule());

            IMapperFactory mapperFactory = engine.BuildMapperFactory();
            sessionFactory = engine.ModelStore.SessionFactory;
            dataMapper = ((IDataMapperAccessor)mapperFactory).DataMapper;
        }
示例#5
0
        protected virtual void SetUpFixture()
        {
            //DateTime start = DateTime.Now;

            configurationSetting = new ConfigurationSetting();
            configurationSetting.Properties.Add("collection2Namespace", "MyBatis.DataMapper.SqlClient.Test.Domain.LineItemCollection2, MyBatis.DataMapper.SqlClient.Test");
            configurationSetting.Properties.Add("nullableInt", "int?");

            string resource = "sqlmap.config";

            try
            {
                IConfigurationEngine engine = new DefaultConfigurationEngine(configurationSetting);
                engine.RegisterInterpreter(new XmlConfigurationInterpreter(resource));
                engine.RegisterModule(new AliasModule());

                IMapperFactory mapperFactory = engine.BuildMapperFactory();
                sessionFactory = engine.ModelStore.SessionFactory;
                dataMapper = ((IDataMapperAccessor)mapperFactory).DataMapper;
                sessionStore = ((IModelStoreAccessor) dataMapper).ModelStore.SessionStore;
            }
            catch (Exception ex)
            {
                Exception e = ex;
                while (e != null)
                {
                    Console.WriteLine(e.Message);
                    Console.WriteLine(e.StackTrace);
                    e = e.InnerException;
                }
                throw;
            }

            if (sessionFactory.DataSource.DbProvider.Id.IndexOf("PostgreSql") >= 0)
            {
                ConvertKey = new KeyConvert(Lower);
            }
            else if (sessionFactory.DataSource.DbProvider.Id.IndexOf("oracle") >= 0)
            {
                ConvertKey = new KeyConvert(Upper);
            }
            else
            {
                ConvertKey = new KeyConvert(Normal);
            }

            //			string loadTime = DateTime.Now.Subtract(start).ToString();
            //			Console.WriteLine("Loading configuration time :"+loadTime);
        }
示例#6
0
        protected virtual void TestFixtureSetUp()
        {
            LogManager.Adapter = new ConsoleOutLoggerFA(new NameValueCollection());
            configurationSetting = new ConfigurationSetting();
            configurationSetting.Properties.Add("collection2Namespace", "MyBatis.DataMapper.Sqlite.Test.Domain.LineItemCollection2, MyBatis.DataMapper.Sqlite.Test");
            configurationSetting.Properties.Add("nullableInt", "int?");

            ConfigurationEngine = new DefaultConfigurationEngine(configurationSetting);
            ConfigurationEngine.RegisterInterpreter(new XmlConfigurationInterpreter("SqlMap.config"));
            ConfigurationEngine.RegisterModule(new AliasModule());

            IMapperFactory mapperFactory = ConfigurationEngine.BuildMapperFactory();
            sessionFactory = ConfigurationEngine.ModelStore.SessionFactory;
            dataMapper = ((IDataMapperAccessor)mapperFactory).DataMapper;
        }
示例#7
0
        /// <summary>
        /// Builds the mapped statements.
        /// </summary>
        /// <param name="store">The store.</param>
        /// <param name="configurationSetting"></param>
        private void BuildMappedStatements(IConfigurationStore store, ConfigurationSetting configurationSetting)
        {
            for (int i = 0; i < store.Statements.Length; i++)
            {
                //对应statement  select update delete insert procedure节点配置信息
                IConfiguration statementConfig = store.Statements[i];
                IMappedStatement mappedStatement = null;

                switch (statementConfig.Type)//statements节点下的6大类型节点信息
                {
                    case ConfigConstants.ELEMENT_STATEMENT:
                        mappedStatement = BuildStatement(statementConfig, configurationSetting);
                        break;
                    case ConfigConstants.ELEMENT_SELECT:
                        mappedStatement = BuildSelect(statementConfig, configurationSetting);
                        break;
                    case ConfigConstants.ELEMENT_INSERT:
                        mappedStatement = BuildInsert(statementConfig, configurationSetting);
                        break;
                    case ConfigConstants.ELEMENT_UPDATE:
                        mappedStatement = BuildUpdate(statementConfig, configurationSetting);
                        break;
                    case ConfigConstants.ELEMENT_DELETE:
                        mappedStatement = BuildDelete(statementConfig, configurationSetting);
                        break;
                    case ConfigConstants.ELEMENT_PROCEDURE:
                        mappedStatement = BuildProcedure(statementConfig, configurationSetting);
                        break;
                    case ConfigConstants.ELEMENT_SQL:
                        break;
                    default:
                        throw new ConfigurationException("Cannot build the statement, cause invalid statement type '" + statementConfig.Type + "'.");

                }
                if (mappedStatement!=null)
                {
                    //最后的结果是加入到了DefaultModleStore中
                    modelStore.AddMappedStatement(mappedStatement);
                }
            }
        }
        public void Can_plug_HybridWebThreadSessionStore()
        {
            string uri = "assembly://MyBatis.DataMapper.SqlClient.Test/bin.Debug/SqlMap_Test_Configure.config";
            IResource resource = ResourceLoaderRegistry.GetResource(uri);

            ConfigurationSetting setting = new ConfigurationSetting();
            setting.SessionStore = new HybridWebThreadSessionStore("test");
            setting.ValidateMapperConfigFile = true;

            IConfigurationEngine engine = new DefaultConfigurationEngine(setting);
            engine.RegisterInterpreter(new XmlConfigurationInterpreter(resource));

            IMapperFactory mapperFactory = engine.BuildMapperFactory();
            IDataMapper dataMapper = ((IDataMapperAccessor)mapperFactory).DataMapper;

            Account account = dataMapper.QueryForObject<Account>("GetAccountViaResultClass", 1);

            Assert.AreEqual(1, account.Id, "account.Id");
            Assert.AreEqual("Joe", account.FirstName, "account.FirstName");
            Assert.AreEqual("Dalton", account.LastName, "account.LastName");
            Assert.AreEqual("*****@*****.**", account.EmailAddress, "account.EmailAddress");
        }
示例#9
0
        /// <summary>
        /// Builds an <see cref="Insert"/> for a insert configuration.
        /// </summary>
        /// <param name="statementConfig">The statement config.</param>
        /// <param name="configurationSetting"></param>
        private IMappedStatement BuildInsert(IConfiguration statementConfig, ConfigurationSetting configurationSetting)
        {
            BaseStatementDeSerializer insertDeSerializer = new InsertDeSerializer();
            IStatement statement = insertDeSerializer.Deserialize(modelStore, statementConfig, configurationSetting);
            ProcessSqlStatement(statementConfig, statement);
            MappedStatement mappedStatement = new InsertMappedStatement(modelStore, statement);
            Insert insert = (Insert)statement;
            if (insert.SelectKey != null)
            {
                ConfigurationCollection selectKeys = statementConfig.Children.Find(ConfigConstants.ELEMENT_SELECTKEY);
                IConfiguration selectKeyConfig = selectKeys[0];

                ProcessSqlStatement(selectKeyConfig, insert.SelectKey);
                MappedStatement mapStatement = new MappedStatement(modelStore, insert.SelectKey);
                modelStore.AddMappedStatement(mapStatement);
            }

            return BuildCachingStatement(statement, mappedStatement);
        }
示例#10
0
        /// <summary>
        /// Builds a <see cref="Statement"/> for a statement configuration.
        /// </summary>
        /// <param name="statementConfig">The statement config.</param>
        /// <param name="configurationSetting"></param>
        private IMappedStatement BuildStatement(IConfiguration statementConfig, ConfigurationSetting configurationSetting)
        {
            BaseStatementDeSerializer statementDeSerializer = new StatementDeSerializer();
            //解析statement节点属性到类中
            IStatement statement = statementDeSerializer.Deserialize(modelStore, statementConfig, configurationSetting);
            //估计是处理statement节点对应的文本内容  ----->确实如此 此处是个核心 一个statement节点的配置信息 和 对应的内存类
            //处理的结果放在了statement中 包括了要执行的sql语句和参数
            ProcessSqlStatement(statementConfig, statement);

            //具体封装了IDbcommand IDataReader的一些类
            MappedStatement mappedStatement = new MappedStatement(modelStore, statement);

            //放入缓存类中 并返回mappedStatement
            return BuildCachingStatement(statement, mappedStatement);
        }
示例#11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DefaultConfigurationEngine"/> class.
        /// </summary>
        /// <param name="configurationSetting">The configuration setting.</param>
        public DefaultConfigurationEngine(ConfigurationSetting configurationSetting):this()
        {
            Contract.Require.That(configurationSetting, Is.Not.Null).When("retrieving argument ConfigurationSetting in DefaultConfigurationEngine constructor");

            this.configurationSetting = configurationSetting;

            if (configurationSetting.Properties.Count > 0)
            {
                IEnumerator<KeyValuePair<string, string>> properties = configurationSetting.Properties.GetEnumerator();
                while (properties.MoveNext())
                {
                    IConfiguration config = new MutableConfiguration(
                    ConfigConstants.ELEMENT_PROPERTY,
                    properties.Current.Key,
                    properties.Current.Value);
                    configurationStore.AddPropertyConfiguration(config);
                }
            }
        }
示例#12
0
        /// <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());
            }
        }
示例#13
0
        /// <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
            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>
        /// 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
            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());
            }
        }
示例#15
0
        /// <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());
            }
        }
        public void CodeConfigurationMatchesSqlMapConfig()
        {
            #region SqlMapConfig.xml
            /*
            <sqlMapConfig xmlns="http://ibatis.apache.org/dataMapper" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
	            <settings>
		            <setting useStatementNamespaces="true"/>
		            <setting cacheModelsEnabled="false"/>
		            <setting validateSqlMap="false"/>
		            <setting useReflectionOptimizer="false"/>
		            <setting preserveWhitespace="false"/>
	            </settings>	
	            <providers uri="file://providers.config"/>
	            <database>
		            <provider name="SQLite3"/>
		            <dataSource name="ibatisnet.sqlmap" connectionString="Data Source=ibatisnet.sqlite;Version=3;"/>
	            </database>  
	            <alias>
		            <typeAlias alias="Account" type="MyBatis.DataMapper.Sqlite.Test.Domain.Account, MyBatis.DataMapper.Sqlite.Test"/>
	            </alias>  
              <sqlMaps>
		            <sqlMap uri="file://../../Maps/Account.xml"/>
              </sqlMaps>
            </sqlMapConfig>
            */
            #endregion

            // slightly awkward to creating ConfigurationSetting, then engine, then interpreter ???

            ConfigurationSetting settings = new ConfigurationSetting();
            settings.UseStatementNamespaces = true;
            settings.IsCacheModelsEnabled = false;
            settings.ValidateMapperConfigFile = false;
            settings.UseReflectionOptimizer = false;
            settings.PreserveWhitespace = false;

            var engine = new DefaultConfigurationEngine(settings);

            CodeConfigurationInterpreter codeConfig = new CodeConfigurationInterpreter(engine.ConfigurationStore);
            codeConfig.AddDatabase(new SqliteDbProvider(), "Data Source=ibatisnet.sqlite;Version=3;");
            codeConfig.AddAlias(typeof(Account), "Account");
            codeConfig.AddSqlMap("file://../../Maps/Account.xml", true);

            engine.RegisterInterpreter(codeConfig);
            IMapperFactory mapperFactory = engine.BuildMapperFactory();
            IDataMapper localDataMapper = ((IDataMapperAccessor)mapperFactory).DataMapper;

            IConfigurationStore store = engine.ConfigurationStore;
            IConfigurationStore baseStore = ConfigurationEngine.ConfigurationStore;

            assertConfiguration(baseStore.Properties, store.Properties);
            // assertConfiguration(baseStore.Settings, store.Settings);
            assertConfiguration(baseStore.Databases, store.Databases);
            assertConfiguration(baseStore.TypeHandlers, store.TypeHandlers);
            assertConfiguration(baseStore.Alias, store.Alias);
            assertConfiguration(baseStore.CacheModels, store.CacheModels);
            assertConfiguration(baseStore.ResultMaps, store.ResultMaps);
            assertConfiguration(baseStore.Statements, store.Statements);
            assertConfiguration(baseStore.ParameterMaps, store.ParameterMaps);

            InitScript(sessionFactory.DataSource, "../../Scripts/account-init.sql");

            ICollection items = localDataMapper.QueryForList("Account.GetAllAccounts1", null);
            Assert.IsTrue(items.Count > 1);

            items = localDataMapper.QueryForList("Account.GetAllAccounts2", null);
            Assert.IsTrue(items.Count > 1);
        }