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 @   易独  阅读(681)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
乐巴儿 一个有声音的公众号
长按,识别二维码,加关注
点击右上角即可分享
微信分享提示