Nhibernate中实现多数据库支持

Nhibernate中实现多数据库支持

 
  • 摘要:Nhibernate中不直接支持多数据库, 只好在网上找,找到NHibernate Contrib(Burrow)就可以支持多数据库,作了一下心得记录

  应工作需要,使用Nhibernate ,但Nhibernate中不直接支持多数据库, 只好在网上找,找到NHibernate Contrib(Burrow)就可以支持多数据库,其操作可以参考http://www.csharpwin.com/dotnetspace/10445r7676.shtml上面的, 就查看了其源码,作了一下心得记录

先配制 NHibernate Burrow

添加web.config配置信息,读取配置和assembly

<configSections>
<section name="NHibernate.Burrow" type="NHibernate.Burrow.Configuration.NHibernateBurrowCfgSection"/>
</configSections>
<NHibernate.Burrow >
<persistantUnits>
<add name="PersistenceUnit1" nh-config-file="hibernate.cfg.xml"/> //第一个数据库
<add name="PersistenceUnit2" nh-config-file="hibernate2.cfg.xml"/> //第二个数据库
。。。。。。//可加多个
</persistantUnits>
</NHibernate.Burrow>

 

再添加HttpModule Setting 用于管理会话和事务

<httpModules>
  <add name="NHibernate.Burrow.WebUtil.HttpModule" type="NHibernate.Burrow.WebUtil.WebUtilHTTPModule,NHibernate.Burrow.WebUtil"/>
</httpModules>
 

   最主要的实现原理就就 先建一个单例的PersistenceUnitRepo类(其实就PersistenceUnit 的集合,存有所有PersistenceUnit 对象),用来保存PersistenceUnit,

PersistenceUnit对象就是上面的一个<add name="PersistenceUnit1" nh-config-file="hibernate.cfg.xml" />它保存有

public string Name
{
get { return configuration.Name; }
}

internal ISessionFactory SessionFactory
{
get { return sessionFactory; }
}

///<summary>
/// The nhibernate configuration of this session Manager
///</summary>
public Cfg.Configuration NHConfiguration
{
get { return nHConfiguration; }
}

然后一个就是如何操作的问题,我们可以使用NHibernate.Burrow.AppBlock.DAOBases中的 GenericDAO<ReturnT>类来调用

其实现调用主要是这段代码来实现的

internal PersistenceUnit GetPU(System.Type t)
{
if(PersistenceUnits.Count == 0)
throw new PersistenceUnitsNotReadyException();
if (PersistenceUnits.Count == 1)
return PersistenceUnits[0];

foreach (PersistenceUnit pu in persistenceUnits)
{
ISessionFactoryImplementor sfi = (ISessionFactoryImplementor) pu.SessionFactory;

try
{
if (sfi.GetEntityPersister(t.FullName) != null)  //找到所要找的方法
return pu;
}
catch { }
}

throw new GeneralException("Persistence Unit cannot be found for " + t);
}
 

遍例每一个PersistenceUnit  直到找到所要找的方法,最后返回这个方法所在的PersistenceUnit , 在PersistenceUnit 中就有ISessionFactory ,如没有的话就抛出错误

posted @ 2013-05-07 15:57  易独  阅读(668)  评论(0编辑  收藏  举报
乐巴儿 一个有声音的公众号
长按,识别二维码,加关注