在Window Form中使用NHibernate

在Window Form中使用NHibernate也主要是实体配置文件的加载(会话工厂)和对session的管理。

会话工厂
Configuration.BuildSessionFactory()是很昂贵的操作(特别是当有很多实体类的时候),所以一般使用Singleton模式来建立会话工厂来一次性将所有实体配置加载。
Session的管理器
由于建立一个session是比较耗费资源的,所以为了不频繁地打开和关闭session,可以使用ThreadStaticAttribute(具体请看MSDN),或者TLS,比如在张老三的文章中的用法:
public class SessionManager {
   
public static void SetSession( ISession session ) {
      Thread.SetData( Thread.GetNamedDataSlot(
"session"), session );
   }


   
public static ISession GetSession()  {
      
object obj = Thread.GetData( Thread.GetNamedDataSlot("session") );
      
if ( obj == null )
         
throw new Exception( "no session object!" );

      
return (ISession)obj;
   }

}
 //class SessionManager

注意此用法在ASP.NET中就不是好的做法了,道理很简单,每个Request可能会有多个session为其服务,使用TLS的话会在每个Thread上打开一个NHiberante的session,这显然是比较浪费的;为了在一个Request中能共享NHiberante的session,可以使用HttpContext.Current.Items来保存之,这在我的前一个post中已经提到了。

处理多数据库连接

NHibernate的配置中是只有一个数据库连接的,当需要多个不同的数据库连接的时候,可以新增加一个xml配置文件(hibernate.cfg.xml),其内容如:

<hibernate-configuration  xmlns="urn:nhibernate-configuration-2.0" >
    
<session-factory name="NHibernate.Test">
        
<!-- properties -->
        
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
        
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
        
<property name="connection.connection_string">Server=localhost;initial catalog=nhibernate;Integrated Security=SSPI</property>
        
<property name="show_sql">false</property>
        
<property name="dialect">NHibernate.Dialect.MsSql2000Dialect</property>
        
<property name="use_outer_join">true</property>
        
<property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
        
<!-- mapping files -->
        
<mapping assembly="NHibernate.Examples" />
    
</session-factory>
    
</hibernate-configuration>


代码类似于:

        private void Config(string configXmlFile,Type[] types)
        
{            
            
try
            
{
                nConfig 
= new Configuration();
                nConfig.Configure(configXmlFile);

                
for ( int i=0;i<types.Length;i++)
                
{
                    nConfig.AddClass(types[i]);
                }

                nSessionFactory 
= nConfig.BuildSessionFactory();
            }

            
catch(Exception e)
            
{
                
throw e;
            }

        }

另外,请参考codeproject上的一个在winform中使用NHibernate的例子,注意其代码也有一些不合理的地方。
posted @ 2005-01-17 13:03  风满袖  阅读(4313)  评论(4编辑  收藏  举报