• 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 ,如没有的话就抛出错误

  • 相关阅读:
    Leetcode100.相同的树
    Leetcode53. 最大子序列和
    Leetcode35. 搜索插入位置
    Leetcode27.移除元素
    Leetcode 26. 删除排序数组中的重复项
    Leetcode. 1290 二进制链表转整数
    Leetcode.234 回文链表
    Leetcode206.反转链表
    课本 求素数
    循环法求素数 1306 循环求素数10.1.5.253 ====== 1313 筛选法求素数10.1.5.253
  • 原文地址:https://www.cnblogs.com/yexinw/p/3064934.html
Copyright © 2020-2023  润新知