注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

天涯倦客的博客

祝福你朋友永远快乐!

 
 
 

日志

 
 

iBatis.Net的核心类  

2013-09-17 15:23:18|  分类: asp.net |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

   iBatis.NET是我接触Nhibernate之后的第二个ORM框架,我觉得这个框架具有小巧玲珑的特点。如果你想自己开发一个ORM框架的话,我觉得iBatis.net肯定是你必须要熟读的,因为它很简洁。如果你深入了解它,你会觉得这种ORM框架的出现是必然的,因为它很接近人们在探索ORM框架的最基本想法。

       我们在自学iBatis.net的时候,都会参考NPetShop这个经典的开源代码。里面有一些核心的类,如ServiceConfig和BaseSqlMapDao,理解这些类对理解iBatis.net的核心是非常重要的。 

 

ibatis.net组件中的核心类:

IBatisNet.DataAccess组件中的DaoManager类:

[csharp] view plaincopy
  1. using IBatisNet.Common;  
  2. using IBatisNet.Common.Utilities;  
  3. using IBatisNet.DataAccess.Interfaces;  
  4. using IBatisNet.DataAccess.SessionStore;  
  5. using System;  
  6. using System.Collections.Specialized;  
  7. using System.Data;  
  8. using System.Reflection;  
  9.   
  10. namespace IBatisNet.DataAccess  
  11. {  
  12.     public class DaoManager : IDaoManager  
  13.     {  
  14.         public const string DEFAULT_CONTEXT_NAME = "_DEFAULT_CONTEXT_NAME";  
  15.   
  16.         protected static HybridDictionary DaoContextMap;  
  17.   
  18.         public string Id { getset; }  
  19.         public IDalSession LocalDaoSession { get; }  
  20.         public IDataSource LocalDataSource { get; }  
  21.         public ISessionStore SessionStore { set; }  
  22.   
  23.         public IDao this[Type daoInterface] { get; }  
  24.   
  25.         public IDalSession BeginTransaction();  
  26.         public IDalSession BeginTransaction(IsolationLevel isolationLevel);  
  27.         public void CloseConnection();  
  28.         public void CommitTransaction();  
  29.         [Obsolete("This method will be removed in a future version, use DomDaoManagerBuilder.Configure."false)]  
  30.         public static void Configure();  
  31.         [Obsolete("This method will be removed in a future version, use DomDaoManagerBuilder.Configure."false)]  
  32.         public static void Configure(string resource);  
  33.         [Obsolete("This method will be removed in a future version, use DomDaoManagerBuilder.Configure."false)]  
  34.         public static void ConfigureAndWatch(ConfigureHandler configureDelegate);  
  35.         [Obsolete("This method will be removed in a future version, use DomDaoManagerBuilder.Configure."false)]  
  36.         public static void ConfigureAndWatch(string resource, ConfigureHandler configureDelegate);  
  37.         public IDao GetDao(Type daoInterface);  
  38.         public DaoSession GetDaoSession();  
  39.         public static IDaoManager GetInstance();  
  40.         public static IDaoManager GetInstance(IDao dao);  
  41.         public static IDaoManager GetInstance(string contextName);  
  42.         public bool IsDaoSessionStarted();  
  43.         public IDalSession OpenConnection();  
  44.         public IDalSession OpenConnection(string connectionString);  
  45.         public void RollBackTransaction();  
  46.     }  
  47. }  



SqlMapDaoSession类:

[csharp] view plaincopy
  1. using IBatisNet.DataAccess;  
  2. using IBatisNet.DataMapper;  
  3. using System;  
  4. using System.Data;  
  5.   
  6. namespace IBatisNet.DataAccess.DaoSessionHandlers  
  7. {  
  8.     public class SqlMapDaoSession : DaoSession  
  9.     {  
  10.         public SqlMapDaoSession(DaoManager daoManager, ISqlMapper sqlMap);  
  11.   
  12.         public override IDbConnection Connection { get; }  
  13.         public override IDataSource DataSource { get; }  
  14.         public override bool IsTransactionStart { get; }  
  15.         public ISqlMapper SqlMap { get; }  
  16.         public override IDbTransaction Transaction { get; }  
  17.   
  18.         public override void BeginTransaction();  
  19.         public override void BeginTransaction(bool openConnection);  
  20.         public override void BeginTransaction(IsolationLevel isolationLevel);  
  21.         public override void BeginTransaction(string connectionString);  
  22.         public override void BeginTransaction(bool openConnection, IsolationLevel isolationLevel);  
  23.         public override void BeginTransaction(string connectionString, IsolationLevel isolationLevel);  
  24.         public override void BeginTransaction(string connectionString, bool openConnection, IsolationLevel isolationLevel);  
  25.         public override void CloseConnection();  
  26.         public override void CommitTransaction();  
  27.         public override void CommitTransaction(bool closeConnection);  
  28.         public override void Complete();  
  29.         public override IDbCommand CreateCommand(CommandType commandType);  
  30.         public override IDbDataAdapter CreateDataAdapter();  
  31.         public override IDbDataAdapter CreateDataAdapter(IDbCommand command);  
  32.         public override IDbDataParameter CreateDataParameter();  
  33.         public override void Dispose();  
  34.         public override void OpenConnection();  
  35.         public override void OpenConnection(string connectionString);  
  36.         public override void RollBackTransaction();  
  37.         public override void RollBackTransaction(bool closeConnection);  
  38.     }  
  39. }  

 

IBatisNet.DataMapper 组件中的DataMapper类:

[csharp] view plaincopy
  1. using IBatisNet.Common;  
  2. using IBatisNet.Common.Utilities.Objects;  
  3. using IBatisNet.Common.Utilities.Objects.Members;  
  4. using IBatisNet.DataMapper.Configuration.Cache;  
  5. using IBatisNet.DataMapper.Configuration.ParameterMapping;  
  6. using IBatisNet.DataMapper.Configuration.ResultMapping;  
  7. using IBatisNet.DataMapper.DataExchange;  
  8. using IBatisNet.DataMapper.MappedStatements;  
  9. using IBatisNet.DataMapper.SessionStore;  
  10. using IBatisNet.DataMapper.TypeHandlers;  
  11. using System;  
  12. using System.Collections;  
  13. using System.Collections.Generic;  
  14. using System.Collections.Specialized;  
  15. using System.Data;  
  16.   
  17. namespace IBatisNet.DataMapper  
  18. {  
  19.     public class SqlMapper : ISqlMapper  
  20.     {  
  21.         public SqlMapper(IObjectFactory objectFactory, AccessorFactory accessorFactory);  
  22.   
  23.         public AccessorFactory AccessorFactory { get; }  
  24.         public DataExchangeFactory DataExchangeFactory { get; }  
  25.         public IDataSource DataSource { getset; }  
  26.         public string Id { get; }  
  27.         public bool IsCacheModelsEnabled { getset; }  
  28.         public bool IsSessionStarted { get; }  
  29.         public ISqlMapSession LocalSession { get; }  
  30.         public HybridDictionary MappedStatements { get; }  
  31.         public IObjectFactory ObjectFactory { get; }  
  32.         public HybridDictionary ParameterMaps { get; }  
  33.         public HybridDictionary ResultMaps { get; }  
  34.         public ISessionStore SessionStore { set; }  
  35.         public TypeHandlerFactory TypeHandlerFactory { get; }  
  36.   
  37.         public void AddCache(CacheModel cache);  
  38.         public void AddMappedStatement(string key, IMappedStatement mappedStatement);  
  39.         public void AddParameterMap(ParameterMap parameterMap);  
  40.         public void AddResultMap(IResultMap resultMap);  
  41.         public ISqlMapSession BeginTransaction();  
  42.         public ISqlMapSession BeginTransaction(bool openConnection);  
  43.         public ISqlMapSession BeginTransaction(IsolationLevel isolationLevel);  
  44.         public ISqlMapSession BeginTransaction(string connectionString);  
  45.         public ISqlMapSession BeginTransaction(bool openNewConnection, IsolationLevel isolationLevel);  
  46.         public ISqlMapSession BeginTransaction(string connectionString, IsolationLevel isolationLevel);  
  47.         public ISqlMapSession BeginTransaction(string connectionString, bool openNewConnection, IsolationLevel isolationLevel);  
  48.         public void CloseConnection();  
  49.         public void CommitTransaction();  
  50.         public void CommitTransaction(bool closeConnection);  
  51.         public ISqlMapSession CreateSqlMapSession();  
  52.         public ISqlMapSession CreateSqlMapSession(string connectionString);  
  53.         public int Delete(string statementName, object parameterObject);  
  54.         public void FlushCaches();  
  55.         public CacheModel GetCache(string name);  
  56.         public string GetDataCacheStats();  
  57.         public IMappedStatement GetMappedStatement(string id);  
  58.         public ParameterMap GetParameterMap(string name);  
  59.         public IResultMap GetResultMap(string name);  
  60.         public object Insert(string statementName, object parameterObject);  
  61.         public ISqlMapSession OpenConnection();  
  62.         public ISqlMapSession OpenConnection(string connectionString);  
  63.         public IDictionary QueryForDictionary(string statementName, object parameterObject, string keyProperty);  
  64.         public IDictionary<K, V> QueryForDictionary<K, V>(string statementName, object parameterObject, string keyProperty);  
  65.         public IDictionary QueryForDictionary(string statementName, object parameterObject, string keyProperty, string valueProperty);  
  66.         public IDictionary<K, V> QueryForDictionary<K, V>(string statementName, object parameterObject, string keyProperty, string valueProperty);  
  67.         public IDictionary<K, V> QueryForDictionary<K, V>(string statementName, object parameterObject, string keyProperty, string valueProperty, DictionaryRowDelegate<K, V> rowDelegate);  
  68.         public IList<T> QueryForList<T>(string statementName, object parameterObject);  
  69.         public IList QueryForList(string statementName, object parameterObject);  
  70.         public void QueryForList<T>(string statementName, object parameterObject, IList<T> resultObject);  
  71.         public void QueryForList(string statementName, object parameterObject, IList resultObject);  
  72.         public IList<T> QueryForList<T>(string statementName, object parameterObject, int skipResults, int maxResults);  
  73.         public IList QueryForList(string statementName, object parameterObject, int skipResults, int maxResults);  
  74.         public IDictionary QueryForMap(string statementName, object parameterObject, string keyProperty);  
  75.         public IDictionary QueryForMap(string statementName, object parameterObject, string keyProperty, string valueProperty);  
  76.         public IDictionary QueryForMapWithRowDelegate(string statementName, object parameterObject, string keyProperty, string valueProperty, DictionaryRowDelegate rowDelegate);  
  77.         public object QueryForObject(string statementName, object parameterObject);  
  78.         public T QueryForObject<T>(string statementName, object parameterObject);  
  79.         public object QueryForObject(string statementName, object parameterObject, object resultObject);  
  80.         public T QueryForObject<T>(string statementName, object parameterObject, T instanceObject);  
  81.         [Obsolete("This method will be remove in future version."false)]  
  82.         public PaginatedList QueryForPaginatedList(string statementName, object parameterObject, int pageSize);  
  83.         public IList<T> QueryWithRowDelegate<T>(string statementName, object parameterObject, RowDelegate<T> rowDelegate);  
  84.         public IList QueryWithRowDelegate(string statementName, object parameterObject, RowDelegate rowDelegate);  
  85.         public void RollBackTransaction();  
  86.         public void RollBackTransaction(bool closeConnection);  
  87.         public int Update(string statementName, object parameterObject);  
  88.     }  
  89. }  


IBatisNet.Common组件中的IBatisNetException类,处理异常信息的类。

[csharp] view plaincopy
  1. using System;  
  2. using System.Runtime.Serialization;  
  3.   
  4. namespace IBatisNet.Common.Exceptions  
  5. {  
  6.     [Serializable]  
  7.     public class IBatisNetException : ApplicationException  
  8.     {  
  9.         public IBatisNetException();  
  10.         public IBatisNetException(Exception ex);  
  11.         public IBatisNetException(string message);  
  12.         protected IBatisNetException(SerializationInfo info, StreamingContext context);  
  13.         public IBatisNetException(string message, Exception inner);  
  14.     }  
  15. }  


 通过列举上面的组件的类,我们大概可以分析出ibatis.net三大组件的作用:

IBatisNet.DataAccess,是访问数据库和与数据库交互的核心组件。

 

IBatisNet.DataMapper,提供数据访问的接口。将SQL从原来硬编码中分离到.xml文件中去。

查询出来的结果通过Map, List, Object方式返回调用层。.NET 2.0推出之后,iBatisNet的DataMapper也支持了泛型,

具有了更强的类型支持。其简单易上手的动态SQL(通过xml标签来配置),使得iBatisNet更加灵活好用。

 

 

 

   /// <summary>
    /// iBatis.NET的核心类 ServiceConfig.
    /// </summary>
    public class ServiceConfig
    {
        static private object synRoot = new object();    //建立一个object对象,在處理多線程的同步時非常有用
        //3:定义一个变量instance来存储创建好的类实例,因为这个变量要在静态方法中使用,所以需要加上static修饰
        static private ServiceConfig instance;     
        private DaoManager daoManager = null;   //定义一个DaoManager类型的daoManager字段

        ///<summary>
        ///1:私有化构造方法,好在内部控制创建实例的数目
        ///</summary>
        private ServiceConfig() { }

        //2:定义一个方法来为客户端提供类实例,这个方法需要定义成类方法(即静态方法),也就是要加上static
        static public ServiceConfig GetInstance()
        {
            if (instance == null)
            {
                //在多线程的程序中,多个线程同时访问单例类,调用GetInstance()方法,会有可能造成创建多个实例在这种情况下,给进行加一把锁来处理
                //lock是确保当一个线程位于代码的临界区时,另一个线程不进入临界区。如果其他线程试图进入锁定代码,则它将一直等,直到对象被释放。
                lock (synRoot)
                {
                    //判断存储实例的变量是否有值
                    if (instance == null)
                    {
                        try
                        {
                            //定义ConfigureHander事件的一个实例handler,并调用Service.Reset作为参数,该事件的作用是
                            IBatisNet.Common.Utilities.ConfigureHandler handler = new ConfigureHandler(ServiceConfig.Reset);  
                            IBatisNet.DataAccess.Configuration.DomDaoManagerBuilder builder = new DomDaoManagerBuilder();
                            builder.ConfigureAndWatch("dao.config", handler);
                            instance = new ServiceConfig();   //如果Instance为空,就创建一个类实例,并把值赋给存储类实例的变量instance. 
                            //返回一个DaoManager实例,"SqlMapDao"为dao.config文件 context 节点id的值
                            instance.daoManager = (DaoManager)DaoManager.GetInstance("SqlMapDao");  
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.Message);
                        }
                    }
                }
            }
            return instance;  //如果Instance不为空,那就直接使用。
        }

        ///<summary>
        ///Reset the singleton
        ///<summary>
        ///<remarks>
        ///Must verity ConfigureHandler signature.
        ///</remarks>
        ///<param name="obj">
        ///</param>
        static public void Reset(object obj)
        {
            instance = null;
        }
      

        //定义一个属性DaoManager,它返回一个DaoManager类的一个实例
        public DaoManager DaoManager
        {
            get
            {
                return daoManager;
            }
        }
    }

 

现在让我们看看ServiceConfig类的具体作用。下面定义一个服务类NewsService,我们通过 IbatisNet.ServiceConfig.GetInstance().DaoManager返回一个DaoManager的一个实例。再通过这个实例进行对数据库的操作。

   public class NewsService
    {
        #region Private Fields
        private INewsDao newsDao;
        private static NewsService instance = new NewsService();
        private DaoManager daoManager = null;

        #endregion

        public static NewsService GetInstance()
        {
            return instance;
        }

        public NewsService()
        {
            daoManager = IbatisNet.ServiceConfig.GetInstance().DaoManager;
            newsDao = daoManager.GetDao(typeof(INewsDao)) as INewsDao;
        }

        public object InsertNews(Domain.News news)
        {
            return this.newsDao.InsertNews(news);
        }

        public Domain.News GetNewsById(float? newsId)
        {
            return this.newsDao.GetNewsById(newsId);
        }

        public IList<Domain.News> GetNewsList()
        {
            return this.newsDao.GetNewsList();
        }

        public IList<Domain.News> GetNewsListByParameter(Parameter.NewsParameter newsParameter)
        {
            return this.newsDao.GetNewsListByParameter(newsParameter);
        }

        public IList<Domain.News> GetNewsListByAnyWhere(string strQueryString)
        {
            Parameter.NewsParameter newsParameter = new Parameter.NewsParameter();
            newsParameter.UnlimitedQuery = strQueryString;
            return this.newsDao.GetNewsListByAnyWhere(newsParameter);
        }

        public int UpdateNews(Domain.News news)
        {
            return this.newsDao.UpdateNews(news);
        }

        public int UpdateNewsByParameter(Parameter.NewsParameter newsParameter)
        {
            return this.newsDao.UpdateNewsByParameter(newsParameter);
        }

        public object DeleteNews(Domain.News news)
        {
            return this.newsDao.DeleteNews(news);
        }

        public object DeleteNewsById(float? newsId)
        {
            return this.newsDao.DeleteNewsById(newsId);
        }

        public object DeleteNewsByParameter(Parameter.NewsParameter newsParameter)
        {
            return this.newsDao.DeleteNewsByParameter(newsParameter);
        }

        public object DeleteNewsByAnyWhere(Parameter.NewsParameter newsParameter)
        {
            return this.newsDao.DeleteNewsByAnyWhere(newsParameter);
        }
    }

 

  

自定义的BaseSqlMapDao类,数据库操作类,类似于OracleHelper后SqlHelper。

转自:http://blog.csdn.net/byondocean/article/details/5785351
  评论这张
 
阅读(892)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017