NHibernate 配置文件的处理和使用多数据库的多层架构思路(第一部分)

 

 开发环境: windows server 2003 sp2 + VS2005 + SQL Server 2005 + NHibernate-1.2.0.GA

(1) 配置文件的处理
        主要是谈NHibernate的配置文件的数据库连接字符串的加密处理方法.关于配置文件的设置, renrenqq 的文章《NHibernate的灵活配置》   讲的非常详细,大家可以看看!

        NHibernate的配置文件的代码部分可以放在程序的配置文件中(Win Forms的App.config,Web Forms 的Web.config),然后使用企业库管理工具来加密,但是有个问题,该配置方式不能配置映射类,需要通过程序的方式加入,而且也造成应用程序配置文件信息过大!当然,你需要程序的方式加入,而且程序配置文件信息量的大小不是考虑的问题,无疑这个方法可用。

        但是,如果我需要在NHibernate的配置文件中配置映射类呢?就需要为之建一个名为hibernate.cfg.xml的文件。配置映射类的问题解决了!但是数据库连接字符串直接放在里面,没有被加密,很不安全。如果我们把NHibernate的配置文件作为资源嵌入到程序集,似乎可用解决安全问题,但是又出现新的问题,那就是部署。因为用户部署时,是需要重新设置数据库地址,名称,用户名,密码等值的。

        那么解决方案如下:

        在NHibernate的配置文件不加入数据库连接字符串,而仍旧把数据库连接字符串还是放在原来的程序的配置文件中,这样可以使用企业库管理工具来加密。然后在程序中,取出该值后用Configuration的方法AddProperties()加进去,就解决问题了。建议此时的NHibernate的配置文件还是采用资源嵌入到程序集的方式。(没有秘密也不想让你看见!)

        我再多说一个问题,然后我们可以通过对程序配置文件中字符串的增、删、改来完成多个数据库连接字符串的信息,然后再Configuration的方法AddProperties(),来加入需要的数据库连接字符串,就可以完成Hibernate的对多数据库的应用。可能实际的应用中可能需要配置映射类重新处理,或者说在NHibernate的配置文件中不加入配置映射类,然后通过Configuration的方法AddAssembly来加入。

这样就Game Over 了!

详细代码见下面!

呵呵,也许大家早就想到这个方法了,献丑了!

(2) 多层架构思路

一、底层

       包含三个类:

        首先是 Session 的创建类 SessionFactory,由它来提供各个数据库 Session 的创建,并缓存所有Session。每个数据库对应建一个项目的持久层,该项目的程序集名称就是可以来唯一标识各个Session。

    然后是实体的通用操作类,提供一些通用的操作,最基本CRUD,还有列出所有对象等等一些操作。它代替不了数据访问层,但是在数据访问层中使用它既方便,整体的结构也清晰。该类采用范型的理由是,得到的对象获得对象列表都是直接转换了的,不需要在数据访问层中再转换。但是这也意味在数据访问层中,操作每个实体时各个建一个该通用类的对象。权衡利弊,我认为采用采用范型是值得的!我们在后面的数据访问层中可以看到。

     由于是针对多个数据库操作,所以提供了这个类对外提供各个数据操作的各个通用实体对象!(有点拗口!)
在该类中,我们只举了操作一个数据库的例子,如果你看了代码,发现扩充到多个数据库也是非常简单的!但是,这里提醒以下,针对多个数据库的概念是多个数据库已经存在,不是动态创建的!因为动态创建数据库的话,那么持久层类和其配置文件也动态创建吗?或许有其它解决办法,但是本文不针对动态创建数据库。

        以下便是三个类的代码,里面有详细的注释:

None.gif // -----------------------------------------------------------------------------------------
None.gif
//  模块编号:
None.gif
//  文件名: SessionFactory.cs
None.gif
//  描述: SessionFactory 类
None.gif
//  作者:ChenJie 
None.gif
//  编写日期:2007-5-11
None.gif
//  Copyright 2007
None.gif
// -----------------------------------------------------------------------------------------
None.gif
using  System;
None.gif
using  System.Collections;
None.gif
using  System.Collections.Generic;
None.gif
using  System.Reflection;
None.gif
using  System.Data;
None.gif
using  NHibernate;
None.gif
using  NHibernate.Cfg;
None.gif
using  NHibernate.Tool.hbm2ddl;
None.gif
None.gif
namespace  Novelty.CustomSystem.NHibernateOperation.NHibernateModule
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
InBlock.gif    
/// Session的创建类,属于单件模式(Singleton Pattern)
ExpandedSubBlockEnd.gif    
/// </summary>

InBlock.gif    public sealed class SessionFactory
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
ContractedSubBlock.gifExpandedSubBlockStart.gif        
私有变量#region 私有变量
InBlock.gif        
//保存所有Session
InBlock.gif
        private Dictionary<string, ISession> dicSessions = new Dictionary<string, ISession>(StringComparer.InvariantCultureIgnoreCase);
ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif        
构造函数#region 构造函数
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 构造函数
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        SessionFactory()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{            
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif        
嵌套类#region 嵌套类
InBlock.gif        
class Nested
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
static Nested()
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
ExpandedSubBlockEnd.gif            }

InBlock.gif            
internal static readonly SessionFactory instance = new SessionFactory();
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif        
属性#region 属性
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 唯一实例
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public static SessionFactory Instance
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
get
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return Nested.instance;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif        
实现方法#region 实现方法
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 通过 NHibernate 的配置文件(hibernate.cfg.xml)读取 NHibernate 配置信息。本例中采用的是将 NHibernate 的配置文件附加到该项目的程序集中。
InBlock.gif        
/// 该配置文件中不包含程序集名称,通过 cfg.AddAssembly(assemblyName); 语句来添加。
InBlock.gif        
/// 针对一个数据库就缓存了一个session, 本例中是通过程序集名称标识唯一的session。
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="assemblyName">配置映射类的程序集名称</param>
InBlock.gif        
/// <param name="nhibernateConfigName">NHibernate 的配置文件名称</param>
InBlock.gif        
/// <param name="connectionString">数据路字符串连接</param>
ExpandedSubBlockEnd.gif        
/// <returns>ISession</returns>

InBlock.gif        public ISession OpenSession(string assemblyName, string nhibernateConfigName, string connectionString)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            ISession session 
= null;
InBlock.gif            
if (string.IsNullOrEmpty(connectionString) || string.IsNullOrEmpty(nhibernateConfigName) || string.IsNullOrEmpty(connectionString))
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return null;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
//锁定 dicSessions 字典
InBlock.gif
            lock (dicSessions)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                Configuration cfg 
= GetConfiguration(assemblyName, nhibernateConfigName, connectionString);
InBlock.gif                
if (dicSessions.ContainsKey(assemblyName))
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    session 
= dicSessions[assemblyName];
ExpandedSubBlockEnd.gif                }

InBlock.gif                
else
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{                    
InBlock.gif                    ISessionFactory sessions 
= cfg.BuildSessionFactory();
InBlock.gif                    session 
= sessions.OpenSession();
InBlock.gif                    dicSessions.Add(assemblyName, session);
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            
return session;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 获得 Configuration 对象
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="assemblyName">配置映射类的程序集名称</param>
InBlock.gif        
/// <param name="nhibernateConfigName">NHibernate 的配置文件名称</param>
InBlock.gif        
/// <param name="connectionString">数据路字符串连接</param>
ExpandedSubBlockEnd.gif        
/// <returns>Configuration 对象</returns>

InBlock.gif        public Configuration GetConfiguration(string assemblyName, string nhibernateConfigName, string connectionString)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
//复制到应用程序的 bin 目录下
InBlock.gif            
//Configuration cfg = new Configuration().Configure();                    
InBlock.gif            
//附加在程序集中
InBlock.gif
            Configuration cfg = new Configuration().Configure(Assembly.GetExecutingAssembly(), nhibernateConfigName);
InBlock.gif            
//添加程序集
InBlock.gif            
//如果程序集很大,将导致速度很慢!解决方案如下:
InBlock.gif            
//把该方法该为范型方法: public Configuration GetConfiguration<T>(string nhibernateConfigName, string connectionString)
InBlock.gif            
//然后在写一个方法添加类: (1)首先cfg.AddClass(typeof(T)); (2)将与T相关的类一并添加进去!(一对一,一对多或是多对多的类之间都是有关系的)
InBlock.gif
            if (!string.IsNullOrEmpty(assemblyName))
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                cfg.AddAssembly(assemblyName);
ExpandedSubBlockEnd.gif            }
            
InBlock.gif            
if (!string.IsNullOrEmpty(connectionString))
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                Hashtable properties 
= new Hashtable();
InBlock.gif                properties.Add(NHibernate.Cfg.Environment.ConnectionString, connectionString);
InBlock.gif                cfg.AddProperties(properties);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
return cfg;
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif        
#endregion

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif

 

None.gif // -----------------------------------------------------------------------------------------
None.gif
//  模块编号:
None.gif
//  文件名: EntityControl.cs
None.gif
//  描述: EntityControl 实体类
None.gif
//  作者:ChenJie 
None.gif
//  编写日期:2007-5-11
None.gif
//  Copyright 2007
None.gif
// -----------------------------------------------------------------------------------------
None.gif
using  System;
None.gif
using  System.Reflection;
None.gif
using  System.Collections;
None.gif
using  System.Collections.Generic;
None.gif
using  System.Text;
None.gif
using  System.Data;
None.gif
using  NHibernate;
None.gif
using  NHibernate.Cfg;
None.gif
using  NHibernate.Expression;
None.gif
using  NHibernate.Engine;
None.gif
using  NHibernate.SqlTypes;
None.gif
using  NHibernate.SqlCommand;
None.gif
None.gif
namespace  Novelty.CustomSystem.NHibernateOperation.NHibernateModule
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
InBlock.gif    
/// 实体通用操作类
ExpandedSubBlockEnd.gif    
/// </summary>

InBlock.gif    public class EntityControl<T>
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
ContractedSubBlock.gifExpandedSubBlockStart.gif        
私有变量#region 私有变量
InBlock.gif        
private ISession session;
ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif        
内部成员变量#region 内部成员变量
InBlock.gif        
private string _assemblyName;
InBlock.gif        
private string _nhibernateConfigName;
InBlock.gif        
private string _connectionString;
ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif        
构造函数#region 构造函数
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 默认的构造函数
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public EntityControl()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{            
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 构造函数
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="assemblyName">程序集名称</param>
InBlock.gif        
/// <param name="nhibernateConfigName">NHibernate 的配置文件名称</param>
ExpandedSubBlockEnd.gif        
/// <param name="connectionString">数据路字符串连接</param>

InBlock.gif        public EntityControl(string assemblyName, string nhibernateConfigName, string connectionString)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            session 
= SessionFactory.Instance.OpenSession(assemblyName, nhibernateConfigName, connectionString);
InBlock.gif            _assemblyName 
= assemblyName;
InBlock.gif            _nhibernateConfigName 
= nhibernateConfigName;
InBlock.gif            _connectionString 
= connectionString;
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif        
属性#region 属性
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 程序集名称
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public string AssemblyName
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
get
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return _assemblyName;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
set
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if (_assemblyName == value)
InBlock.gif                    
return;
InBlock.gif                _assemblyName 
= value;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// NHibernate 的配置文件名称
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public string NhibernateConfigName
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
get
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return _nhibernateConfigName;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
set
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if (_nhibernateConfigName == value)
InBlock.gif                    
return;
InBlock.gif                _nhibernateConfigName 
= value;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 数据路字符串连接
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public string ConnectionString
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
get
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return _connectionString;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
set
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if (_connectionString == value)
InBlock.gif                    
return;
InBlock.gif                _connectionString 
= value;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif        
方法#region 方法       
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 增加实体对象
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// <param name="entity">实体对象</param>

InBlock.gif        public void AddEntity(T entity)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{            
InBlock.gif            
using (ITransaction transaction = session.BeginTransaction())
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
try
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    session.Save(entity);
InBlock.gif                    transaction.Commit();
ExpandedSubBlockEnd.gif                }

InBlock.gif                
catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    transaction.Rollback();
InBlock.gif                    
//记录日志, 抛出异常, 不包装异常 
InBlock.gif
                    ExceptionFacade.LogAndThrowAndNoWrapPolicy(ex);
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 更新实体对象
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="entity">实体对象</param>
ExpandedSubBlockEnd.gif        
/// <param name="key">关键字</param>

InBlock.gif        public void UpdateEntity(T entity, Object key)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{            
InBlock.gif            
using (ITransaction transaction = session.BeginTransaction())
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
try
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    session.Update(entity, key);
InBlock.gif                    transaction.Commit();
ExpandedSubBlockEnd.gif                }

InBlock.gif                
catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    transaction.Rollback();
InBlock.gif                    
//记录日志, 抛出异常, 不包装异常 
InBlock.gif
                    ExceptionFacade.LogAndThrowAndNoWrapPolicy(ex);
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 删除实体对象
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// <param name="entity">实体对象</param>

InBlock.gif        public void DeleteEntity(T entity)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{            
InBlock.gif            
using (ITransaction transaction = session.BeginTransaction())
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
try
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    session.Delete(entity);
InBlock.gif                    transaction.Commit();
ExpandedSubBlockEnd.gif                }

InBlock.gif                
catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    transaction.Rollback();
InBlock.gif                    
//记录日志, 抛出异常, 不包装异常 
InBlock.gif
                    ExceptionFacade.LogAndThrowAndNoWrapPolicy(ex);
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 获得实体对象
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="key">关键字</param>
ExpandedSubBlockEnd.gif        
/// <returns></returns>

InBlock.gif        public T GetEntity(Object key)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            T entity 
= default(T);            
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                entity 
= session.Load<T>(key);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
//记录日志, 抛出异常, 不包装异常 
InBlock.gif
                ExceptionFacade.LogAndThrowAndNoWrapPolicy(ex);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
return entity;
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 获得首行首列的值,类似执行 ExecuteScalar
InBlock.gif        
/// 查询结果一般只有一条
InBlock.gif        
/// 举例:hql = "SELECT MAX(systemLog.SystemLogId) FROM SystemLogInfo AS systemLog";
InBlock.gif        
/// </summary>
InBlock.gif        
/// <typeparam name="Y">类型</typeparam>
InBlock.gif        
/// <param name="hql">NHibernate 查询语句</param>
InBlock.gif        
/// <param name="defaultVale">默认值</param>
ExpandedSubBlockEnd.gif        
/// <returns></returns>

InBlock.gif        public Y GetDataFieldValue<Y>(string hql, Y defaultVale)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Y dataFieldValue 
= defaultVale;            
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                IQuery query 
= session.CreateQuery(hql);
InBlock.gif                IEnumerator
<Y> itor = query.Enumerable<Y>().GetEnumerator();
InBlock.gif                itor.MoveNext();
InBlock.gif                
try
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    dataFieldValue 
= itor.Current;
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockStart.gifContractedSubBlock.gif                
catch dot.gif{ }
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
//记录日志, 抛出异常, 不包装异常 
InBlock.gif
                ExceptionFacade.LogAndThrowAndNoWrapPolicy(ex);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
return dataFieldValue;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 获得实体的数目
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="entityName">实体名称</param>
ExpandedSubBlockEnd.gif        
/// <returns>实体的数目</returns>

InBlock.gif        public int GetCountOfEntities(string entityName)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
int count = 0;
InBlock.gif            StringBuilder sb 
= new StringBuilder();
InBlock.gif            sb.Append(
"SELECT COUNT(*) FROM ");
InBlock.gif            sb.Append(entityName);            
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                IQuery query 
= session.CreateQuery(sb.ToString());
InBlock.gif                IEnumerator itor 
= query.Enumerable().GetEnumerator();
InBlock.gif                itor.MoveNext();
InBlock.gif                count 
= Convert.ToInt32(itor.Current);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
//记录日志, 抛出异常, 不包装异常 
InBlock.gif
                ExceptionFacade.LogAndThrowAndNoWrapPolicy(ex);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
return count;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 获得所有的实体对象列表
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// <returns>对象列表</returns>

InBlock.gif        public IList<T> GetEntities()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            IList
<T> entities = null;            
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                entities 
= session.CreateCriteria(typeof(T)).List<T>();
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
//记录日志, 抛出异常, 不包装异常 
InBlock.gif
                ExceptionFacade.LogAndThrowAndNoWrapPolicy(ex);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
return entities;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 通过条件获得实体对象列表
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="propertyName">属性</param>
InBlock.gif        
/// <param name="value">属性值</param>
ExpandedSubBlockEnd.gif        
/// <returns>对象列表</returns>

InBlock.gif        public IList<T> GetEntities(string propertyName, object value)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            IList
<T> entities = null;            
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                ICriteria criteria 
= session.CreateCriteria(typeof(T));
InBlock.gif                criteria.Add(Expression.Eq(propertyName, value));
InBlock.gif                entities 
= criteria.List<T>();
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
//记录日志, 抛出异常, 不包装异常 
InBlock.gif
                ExceptionFacade.LogAndThrowAndNoWrapPolicy(ex);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
return entities;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 执行 SQL 语句并返回对象列表
InBlock.gif        
/// 这个方法不能用,原因有二:
InBlock.gif        
/// 一、这里NH的地盘,下面两个方法能完成这个功能。
InBlock.gif        
/// 二、对于一对多的情况,反射的对象有问题,因为无法处理处理构造函数。
InBlock.gif        
/// 这个方法放在这里是为了开阔一下思路。比如说,需要批量删除。当然,这个又涉及到参数的问题了!
InBlock.gif        
/// 我不喜欢直接将参数拼到 sql 语句中,而是采用后来加载的方式!
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="sql">SQL 语句</param>
ExpandedSubBlockEnd.gif        
/// <returns>查询的结果列表</returns>

InBlock.gif        [Obsolete("Do not call this method.")]
InBlock.gif        
public IList<T> GetEntitiesByExecuteSQL(string sql)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            IList
<T> entities = new List<T>();
InBlock.gif            Configuration cfg 
= SessionFactory.Instance.GetConfiguration(_assemblyName, _nhibernateConfigName, _connectionString);
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
using (ISessionFactoryImplementor s = (ISessionFactoryImplementor)cfg.BuildSessionFactory())
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
using (IDbConnection conn = s.OpenConnection())
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        IDbCommand cmd 
= conn.CreateCommand();
InBlock.gif                        cmd.CommandType 
= CommandType.Text;
InBlock.gif                        cmd.CommandText 
= sql;
InBlock.gif                        
using (IDataReader dr = cmd.ExecuteReader())
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                            
int fieldCount = 0;
InBlock.gif                            
object[] values = null;
InBlock.gif                            
while (dr.Read())
ExpandedSubBlockStart.gifContractedSubBlock.gif                            
dot.gif{
InBlock.gif                                
if (fieldCount == 0)
ExpandedSubBlockStart.gifContractedSubBlock.gif                                
dot.gif{
InBlock.gif                                    fieldCount 
= dr.FieldCount;
InBlock.gif                                    values 
= new Object[fieldCount];
ExpandedSubBlockEnd.gif                                }

InBlock.gif                                
for (int i = 0; i < fieldCount; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                                
dot.gif{
InBlock.gif                                    values[i] 
= dr.GetValue(i);
ExpandedSubBlockEnd.gif                                }

InBlock.gif                                Type t 
= typeof(T);
InBlock.gif                                T obj 
= (T)Activator.CreateInstance(t, values);
InBlock.gif                                entities.Add(obj);
ExpandedSubBlockEnd.gif                            }

ExpandedSubBlockEnd.gif                        }

ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
//记录日志, 抛出异常, 不包装异常 
InBlock.gif
                ExceptionFacade.LogAndThrowAndNoWrapPolicy(ex);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
return entities;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 执行 sql 语句查询获得实体对象列表  
InBlock.gif        
/// 举例:
InBlock.gif        
/// sql = "SELECT * FROM SystemLog";
InBlock.gif        
/// 注意:FROM 后是表的名称
InBlock.gif        
/// /// </summary>
InBlock.gif        
/// <param name="sql">sql 查询语句</param>
ExpandedSubBlockEnd.gif        
/// <returns>对象列表</returns>

InBlock.gif        public IList<T> GetEntitiesBySQL(string sql)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            IList
<T> entities = null;            
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                entities 
= session.CreateSQLQuery(sql).AddEntity(typeof(T)).List<T>();
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
//记录日志, 抛出异常, 不包装异常 
InBlock.gif
                ExceptionFacade.LogAndThrowAndNoWrapPolicy(ex);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
return entities;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 通过 NHibernate 查询语句获得实体对象列表
InBlock.gif        
/// 举例:hql = "FROM SystemLogInfo WHERE UserSerial =1";     
InBlock.gif        
/// 注意:FROM 后是实体的名称
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="hql">NHibernate 查询语句</param>
ExpandedSubBlockEnd.gif        
/// <returns></returns>

InBlock.gif        public IList<T> GetEntitiesByHQL(string hql)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            IList
<T> entities = null;            
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                entities 
= session.CreateQuery(hql).List<T>();
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
//记录日志, 抛出异常, 不包装异常 
InBlock.gif
                ExceptionFacade.LogAndThrowAndNoWrapPolicy(ex);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
return entities;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 将Ilist<T> 转换成 DataSet
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="list"></param>
ExpandedSubBlockEnd.gif        
/// <returns></returns>

InBlock.gif        public DataSet ConvertToDataSet(IList<T> list)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (list == null || list.Count <= 0)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return null;
ExpandedSubBlockEnd.gif            }

InBlock.gif            DataSet ds 
= new DataSet();
InBlock.gif            DataTable dt 
= new DataTable(typeof(T).Name);
InBlock.gif            DataColumn column;
InBlock.gif            DataRow row;
InBlock.gif            PropertyInfo[] myPropertyInfo 
= typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
InBlock.gif            
foreach (T t in list)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if (t == null)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
continue;
ExpandedSubBlockEnd.gif                }

InBlock.gif                row 
= dt.NewRow();
InBlock.gif                
for (int i = 0, j = myPropertyInfo.Length; i < j; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    PropertyInfo pi 
= myPropertyInfo[i];
InBlock.gif                    
string name = pi.Name;                    
InBlock.gif                    
if (dt.Columns[name] == null)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        column 
= new DataColumn(name, pi.PropertyType);
InBlock.gif                        dt.Columns.Add(column);
ExpandedSubBlockEnd.gif                    }

InBlock.gif                    row[name] 
= pi.GetValue(t, null);
ExpandedSubBlockEnd.gif                }

InBlock.gif                dt.Rows.Add(row);
ExpandedSubBlockEnd.gif            }

InBlock.gif            ds.Tables.Add(dt);
InBlock.gif            
return ds;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockEnd.gif        
#endregion

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif

 

None.gif // -----------------------------------------------------------------------------------------
None.gif
//  模块编号:
None.gif
//  文件名: CommonDatabaseOperation.cs
None.gif
//  描述: CommonDatabaseOperation实体类
None.gif
//  作者:ChenJie 
None.gif
//  编写日期:2007-5-11
None.gif
//  Copyright 2007
None.gif
// -----------------------------------------------------------------------------------------
None.gif
using  System;
None.gif
using  System.Collections.Generic;
None.gif
using  System.Configuration;
None.gif
using  Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
None.gif
using  Microsoft.Practices.EnterpriseLibrary.Data;
None.gif
using  Microsoft.Practices.EnterpriseLibrary.Data.Configuration;
None.gif
using  Novelty.CustomSystem.NHibernateOperation.NHibernateModule;
None.gif
None.gif
namespace  Novelty.CustomSystem.NHibernateOperation
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
InBlock.gif    
/// 提供各个实体的类
ExpandedSubBlockEnd.gif    
/// </summary>

InBlock.gif    public class CommonDatabaseOperation<T>
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
ContractedSubBlock.gifExpandedSubBlockStart.gif        
常量#region 常量
InBlock.gif        
<summary>
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// 默认的数据库标识符
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        private const string DEFAULT_DATABASE_IDENTIFIER = "SystemDatabase";
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 配置映射类的程序集名称
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        private const string ASSESMBLY_NAME = "Novelty.Model";   
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// NHibernate 的配置文件名称
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        private const string NHIBERNATE_CONFIG_NAME = "Novelty.CustomSystem.NHibernateOperation.hibernate.cfg.xml";
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 数据路字符串连接
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        private readonly string connectionString;        
ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif         
构造函数#region 构造函数
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 构造函数
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        CommonDatabaseOperation()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{   
InBlock.gif            SystemConfigurationSource systemConfigurationSource 
= new SystemConfigurationSource();
InBlock.gif            DatabaseConfigurationView databaseConfigurationView 
= new DatabaseConfigurationView(systemConfigurationSource);
InBlock.gif            ConnectionStringSettings connectionStringSettings 
= databaseConfigurationView.GetConnectionStringSettings(databaseConfigurationView.DefaultName);
InBlock.gif            connectionString 
= connectionStringSettings.ConnectionString;
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif        
嵌套类#region 嵌套类
InBlock.gif        
class Nested
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
static Nested()
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
ExpandedSubBlockEnd.gif            }

InBlock.gif            
internal static readonly CommonDatabaseOperation<T> instance = new CommonDatabaseOperation<T>();
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif        
属性#region 属性
ExpandedSubBlockStart.gifContractedSubBlock.gif         
/**//// <summary>
InBlock.gif        
/// 唯一实例
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public static CommonDatabaseOperation<T> Instance
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
get
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return Nested.instance;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif        
实现方法#region 实现方法
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 获得 EntityControl 对象。
InBlock.gif        
/// 如果有多个数据库,就有多个对象。
InBlock.gif        
/// 通过实现约定的 name 来读取。
InBlock.gif        
/// 该方法仅实现了一个例子,可以扩展成多个例子。
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="name"></param>
ExpandedSubBlockEnd.gif        
/// <returns></returns>

InBlock.gif        public EntityControl<T> GetEntityControl(string name)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            EntityControl
<T> entityControl = null;
InBlock.gif            
if (string.IsNullOrEmpty(name))
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return null;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
switch (name)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
case DEFAULT_DATABASE_IDENTIFIER:
InBlock.gif                    entityControl 
= new EntityControl<T>(ASSESMBLY_NAME, NHIBERNATE_CONFIG_NAME, connectionString);
InBlock.gif                    
break;
InBlock.gif                
default:
InBlock.gif                    
break;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
return entityControl;
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif

NHibernate 配置文件的处理和使用多数据库的多层架构思路(第二部分)
http://www.cnblogs.com/scucj/archive/2007/05/15/747695.html
NHibernate 配置文件的处理和使用多数据库的多层架构思路(第三部分)
http://www.cnblogs.com/scucj/archive/2007/05/15/747698.html
 

转载于:https://www.cnblogs.com/scucj/archive/2007/05/15/747688.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值