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

       第二种情况:多线程,比如.Net Remoting。
        我现在就是遇见 Net Remoting,才迫使我写这些东西的!每活动的个线程维护一个 session 。 自然就提到了这个属性:System.ThreadStaticAttribute,MSDN是这样描述的:用 ThreadStaticAttribute 标记的 static 字段不在线程之间共享。每个执行线程都有单独的字段实例,并且独立地设置及获取该字段的值。如果在不同的线程中访问该字段,则该字段将包含不同的值。不要为标记为 ThreadStaticAttribute 的字段指定初始值,因为这样的初始化只会发生一次,因此在类构造函数执行时只会影响一个线程。在不指定初始值的情况下,如果它是值类型,可依赖初始化为其默认值的字段,如果它是引用类型,则可依赖初始化为空引用的字段。

        那就不多说了,直接把(一)中底层的两个修改后的类 贴上来,它们是可以在多线程环境下运行的!   CommonDatabaseOperation类没有任何变化!
         EntityControl 类仅修改各个方法中的session 的重新连接和断开!  代码如下:

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            
if (!session.IsConnected)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                session.Reconnect();
ExpandedSubBlockEnd.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                }

InBlock.gif                
finally
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    session.Disconnect();
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            
if (!session.IsConnected)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                session.Reconnect();
ExpandedSubBlockEnd.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                }

InBlock.gif                
finally
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    session.Disconnect();
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            
if (!session.IsConnected)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                session.Reconnect();
ExpandedSubBlockEnd.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                }

InBlock.gif                
finally
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    session.Disconnect();
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            
if (!session.IsConnected)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                session.Reconnect();
ExpandedSubBlockEnd.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            
finally
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                session.Disconnect();
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            
if (!session.IsConnected)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                session.Reconnect();
ExpandedSubBlockEnd.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            
finally
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                session.Disconnect();
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            
if (!session.IsConnected)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                session.Reconnect();
ExpandedSubBlockEnd.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            
finally
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                session.Disconnect();
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            
if (!session.IsConnected)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                session.Reconnect();
ExpandedSubBlockEnd.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            
finally
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                session.Disconnect();
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            
if (!session.IsConnected)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                session.Reconnect();
ExpandedSubBlockEnd.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            
finally
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                session.Disconnect();
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            
if (!session.IsConnected)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                session.Reconnect();
ExpandedSubBlockEnd.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            
finally
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                session.Disconnect();
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            
if (!session.IsConnected)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                session.Reconnect();
ExpandedSubBlockEnd.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            
finally
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                session.Disconnect();
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            
if (!session.IsConnected)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                session.Reconnect();
ExpandedSubBlockEnd.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

      SessionFactory 类改动较大,毕竟就是靠它的对象来为每个线程提供 session.

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)
InBlock.gif    
/// 一个数据库对应一个持久层项目,所以用对应的持久层项目的程序集名称来标识各自的ISessionFactory,Configuration,ISession各个类的对象
ExpandedSubBlockEnd.gif    
/// </summary>

InBlock.gif    public sealed class SessionFactory
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
ContractedSubBlock.gifExpandedSubBlockStart.gif        
私有变量#region 私有变量
InBlock.gif        
//保存所有Sessions,一个数据库对应一个
InBlock.gif
        private Dictionary<string, ISessionFactory> dicSessionFactorys = new Dictionary<string, ISessionFactory>(StringComparer.InvariantCultureIgnoreCase);
InBlock.gif        
//保存所有Configurations, 一个数据库对应一个
InBlock.gif
        private Dictionary<string, Configuration> dicConfigurations = new Dictionary<string, Configuration>(StringComparer.InvariantCultureIgnoreCase);
InBlock.gif        
//保存所有Session
InBlock.gif
        [ThreadStatic]
InBlock.gif        
private Dictionary<string, ISession> dicSessions = null;
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            
if (string.IsNullOrEmpty(connectionString) || string.IsNullOrEmpty(nhibernateConfigName) || string.IsNullOrEmpty(connectionString))
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return null;
ExpandedSubBlockEnd.gif            }
            
InBlock.gif            ISession session 
= GetSessionByName(assemblyName);
InBlock.gif            
if (session == null)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                Configuration cfg 
= GetConfiguration(assemblyName, nhibernateConfigName, connectionString);
InBlock.gif                ISessionFactory sessionnFactory 
= GetSessionFactory(assemblyName, cfg);
InBlock.gif                session 
= sessionnFactory.OpenSession();
InBlock.gif                SaveSeesionByName(assemblyName, session);
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            Configuration cfg 
= null;
InBlock.gif             
//锁定 dicConfigurations 字典
InBlock.gif
            lock (dicConfigurations)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if (!dicConfigurations.ContainsKey(assemblyName))
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
//复制到应用程序的 bin 目录下
InBlock.gif                    
//Configuration cfg = new Configuration().Configure();                    
InBlock.gif                    
//附加在程序集中
InBlock.gif
                    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
                    cfg.AddAssembly(assemblyName);
InBlock.gif                    Hashtable properties 
= new Hashtable();
InBlock.gif                    properties.Add(NHibernate.Cfg.Environment.ConnectionString, connectionString);
InBlock.gif                    cfg.AddProperties(properties);
InBlock.gif                    dicConfigurations[assemblyName] 
= cfg;
ExpandedSubBlockEnd.gif                }

InBlock.gif                
else
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    cfg 
= dicConfigurations[assemblyName];
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            
return cfg;
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif        
实现私有方法#region 实现私有方法
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 通过程序集名获得一个 ISessionFactory 对象
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="assemblyName"></param>
InBlock.gif        
/// <param name="cfg"></param>
ExpandedSubBlockEnd.gif        
/// <returns></returns>

InBlock.gif        private ISessionFactory GetSessionFactory(string assemblyName, Configuration cfg)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            ISessionFactory sessionnFactory 
= null;
InBlock.gif            
lock (dicSessionFactorys)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if (!dicSessionFactorys.ContainsKey(assemblyName))
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    sessionnFactory 
= cfg.BuildSessionFactory();
InBlock.gif                    dicSessionFactorys[assemblyName] 
= sessionnFactory;
ExpandedSubBlockEnd.gif                }

InBlock.gif                
else
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    sessionnFactory 
= dicSessionFactorys[assemblyName];
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            
return sessionnFactory;      
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 通过名称获得Session  保存Session
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="name"></param>
ExpandedSubBlockEnd.gif        
/// <returns></returns>

InBlock.gif        private ISession GetSessionByName(string name)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
/**////延迟初始化
InBlock.gif            if (dicSessions == null)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                dicSessions 
= new Dictionary<string, ISession>(StringComparer.InvariantCultureIgnoreCase);
ExpandedSubBlockEnd.gif            }

InBlock.gif            ISession session 
= null;
InBlock.gif            
if (dicSessions.ContainsKey(name))
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                session 
= dicSessions[name];
InBlock.gif                
if (session != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
if (!session.IsConnected)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        session.Reconnect();
ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            
return session;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 通过名称保存Session
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="name"></param>
ExpandedSubBlockEnd.gif        
/// <param name="value"></param>

InBlock.gif        private void SaveSeesionByName(string name, ISession value)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (value.IsConnected)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                value.Disconnect();
ExpandedSubBlockEnd.gif            }

InBlock.gif            dicSessions[name] 
= value;
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif        
#endregion

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

补充就结束了!
其它四部分地址:
NHibernate 配置文件的处理和使用多数据库的多层架构思路(第一部分)
http://www.cnblogs.com/scucj/archive/2007/05/15/747688.html
NHibernate 配置文件的处理和使用多数据库的多层架构思路(第二部分)
http://www.cnblogs.com/scucj/archive/2007/05/15/747695.html
NHibernate 配置文件的处理和使用多数据库的多层架构思路(第三部分)
http://www.cnblogs.com/scucj/archive/2007/05/15/747698.html
NHibernate 配置文件的处理和使用多数据库的多层架构思路(补充部分一)
http://www.cnblogs.com/scucj/archive/2007/05/16/749192.html

参考资料:
(1) NHibernate的Session管理
http://blog.csdn.net/thebesghost/archive/2006/08/23/1107151.aspx
(2)多线程下WinForm开发应该注意哪些问题?
http://www.cnblogs.com/Cajon/archive/2007/03/21/Multi_Thread_Win_Form.html
(3)NHibernate.Helper Project:
http://blogs.intesoft.net/simon/articles/16.aspx

转载于:https://www.cnblogs.com/scucj/archive/2007/05/16/749227.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值