Mysql
 sql >> Cơ Sở Dữ Liệu >  >> RDS >> Mysql

Cách sử dụng NHibernate với cả máy chủ MySQL và máy chủ Microsoft SQL 2008

Tôi đã gặp khó khăn khá nhiều vài tháng trước. Vấn đề của tôi là với MS Sql Server và Oracle.

Những gì tôi đã làm là tạo hai tệp cấu hình riêng biệt cho nhibernate:

sql.nhibernate.config

<?xml version="1.0" encoding="utf-8"?>
    <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
      <reflection-optimizer use="false" />
      <session-factory name="BpSpedizioni.MsSql">
        <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
        <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
        <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
        <!-- <property name="connection.connection_string">Data Source=(local); Initial Catalog=NHibernate; Trusted_Connection=true;</property> -->
        <property name="current_session_context_class">web</property>
        <property name="adonet.batch_size">100</property>
        <property name="command_timeout">120</property>
        <property name="max_fetch_depth">3</property>
        <property name='prepare_sql'>true</property>
        <property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
        <property name='proxyfactory.factory_class'>NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
        <mapping assembly="BpSpedizioni.Services"/>
      </session-factory>
</hibernate-configuration>

ora.nhibernate.config

<?xml version="1.0" encoding="utf-8"?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <reflection-optimizer use="false" />
  <session-factory name="BpSpedizioni.Oracle">
    <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
    <property name="connection.driver_class">NHibernate.Driver.OracleDataClientDriver</property>
    <property name="dialect">NHibernate.Dialect.Oracle10gDialect</property>
    <!-- <property name="connection.connection_string">Data Source=(local); Initial Catalog=NHibernate; Trusted_Connection=true;</property> -->
    <property name="current_session_context_class">web</property>
    <property name="adonet.batch_size">100</property>
    <property name="command_timeout">120</property>
    <property name="max_fetch_depth">3</property>
    <property name='prepare_sql'>true</property>
    <property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
    <property name='proxyfactory.factory_class'>NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
    <mapping assembly="BpSpedizioni.Services"/>
  </session-factory>
</hibernate-configuration>

Tôi sử dụng lớp đơn giản này để xây dựng Nhibernate SessionFactory của mình:

    public class NHibernateSessionFactory
    {
        private ISessionFactory sessionFactory;

        private readonly string ConnectionString = "";
        private readonly string nHibernateConfigFile = "";

        public NHibernateSessionFactory(String connectionString, string nHConfigFile)
        {
            this.ConnectionString = connectionString;
            this.nHibernateConfigFile = nHConfigFile;
        }

        public ISessionFactory SessionFactory
        {
            get { return sessionFactory ?? (sessionFactory = CreateSessionFactory()); }
        }

        private ISessionFactory CreateSessionFactory()
        {
            Configuration cfg;
            cfg = new Configuration().Configure(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, this.nHibernateConfigFile));

            // With this row below Nhibernate searches for the connection string inside the App.Config.
            // cfg.SetProperty(NHibernate.Cfg.Environment.ConnectionStringName, System.Environment.MachineName);
            cfg.SetProperty(NHibernate.Cfg.Environment.ConnectionString, this.ConnectionString);

#if DEBUG
            cfg.SetProperty(NHibernate.Cfg.Environment.GenerateStatistics, "true");
            cfg.SetProperty(NHibernate.Cfg.Environment.ShowSql, "true");
#endif

            return (cfg.BuildSessionFactory());
        }
    }

Như bạn có thể thấy, tôi chuyển cho NHibernateSessionFactory của mình một chuỗi kết nối (tôi muốn lưu nó trong tệp cấu hình ứng dụng của mình) và tên (không có đường dẫn) của tệp cấu hình nhibernate.

Cá nhân tôi sử dụng một vùng chứa DI (StructureMap) và bạn có thể đạt được điều gì đó rất thú vị khi xác định một lớp đăng ký:

public class NhibernateRegistry : Registry
{
    public NhibernateRegistry()
    {

        For<ISessionFactory>()
        .Singleton()
        .Add(new NHibernateSessionFactory(<oracle connection string>, "ora.nhibernate.config").SessionFactory)
        .Named("OracleSF");

        For<ISession>()
        .HybridHttpOrThreadLocalScoped()
        .Add(o => o.GetInstance<ISessionFactory>("OracleSF").OpenSession())
        .Named("OracleSession");

        For<ISessionFactory>()
        .Singleton()
        .Add(new NHibernateSessionFactory(<ms sql connection string>, "sql.nhibernate.config").SessionFactory)
        .Named("MsSqlSF");

        For<ISession>()
        .HybridHttpOrThreadLocalScoped()
        .Add(o => o.GetInstance<ISessionFactory>("MsSqlSF").OpenSession())
        .Named("MsSqlSession");
    }
}

trong đó bạn có thể sử dụng lớp dịch vụ của tôi được đặt tên hơn là sử dụng lớp đăng ký StructureMap nơi bạn có thể xác định các hàm tạo:

this.For<IOrdersService>()
     .HybridHttpOrThreadLocalScoped()
     .Use<OrdersService>()
     .Ctor<ISession>("sessionMDII").Is(x => x.TheInstanceNamed("OracleSession"))
     .Ctor<ISession>("sessionSpedizioni").Is(x => x.TheInstanceNamed("MsSqlSession"));

Để triển khai Dịch vụ của bạn:

public class OrdersService : IOrdersService
{
        private readonly ISession SessionMDII;
        private readonly ISession SessionSpedizioni;

        public OrdersService(ISession sessionMDII, ISession sessionSpedizioni)
        {
            this.SessionMDII = sessionMDII;
            this.SessionSpedizioni = sessionSpedizioni;
        }

    ...
}


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Cách ghi chính xác các chuỗi UTF-8 vào MySQL thông qua giao diện JDBC

  2. Chuyển đổi cột mysql DATETIME thành epoch giây

  3. mysql - Tạo hiệu suất hàng so với cột

  4. Cách sử dụng NHibernate với cả máy chủ MySQL và máy chủ Microsoft SQL 2008

  5. Nhiều quan hệ với cùng một mô hình CakePHP