Nhibernate 3.0 cookbook学习笔记 配置与架构

NHibernate项目中都有App.config,主要是用来配置项目中的日志与数据库等。

典型的App.config配置文件(这里包括log4net):

View Code
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
      <!--定义配置节点-->
        <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
    </configSections>
    <connectionStrings>
      <!--配置数据库-->
        <add name="db" connectionString="Data Source=.;Initial Catalog=NHCookbook;Integrated Security=True"/>
    </connectionStrings>
    <log4net>
        <appender name="trace"
        type="log4net.Appender.TraceAppender, log4net">
            <layout type="log4net.Layout.PatternLayout, log4net">
                <param name="ConversionPattern"
                value=" %date %level %message%newline" />
            </layout>
        </appender>
        <root>
            <level value="ALL" />
            <appender-ref ref="trace" />
        </root>
        <logger name="NHibernate">
            <level value="INFO" />
        </logger>
        <!--<logger name="MyApp.Project.SomeNamespace.Foo">
      <level value="WARN" />
    </logger>-->
        <logger name="NHibernate.SQL">
            <level  value="DEBUG" />
        </logger>
    </log4net>
  
    <hibernate-configuration
  xmlns="urn:nhibernate-configuration-2.2">
        <session-factory>
          <!--指定代理工厂类-->
            <property name="proxyfactory.factory_class">
                NHibernate.ByteCode.Castle.ProxyFactoryFactory,
                NHibernate.ByteCode.Castle
            </property>
          <!--数据库类型-->
            <property name="dialect">
                NHibernate.Dialect.MsSql2008Dialect,
                NHibernate
            </property>
          <!--数据库名-->
            <property name="connection.connection_string_name">
                db
            </property>
          <!--数据库并发数-->
            <property name="adonet.batch_size">
                100
            </property>
          <!--映射的类名-->
            <mapping assembly="Eg.Core"/>
        </session-factory>
    </hibernate-configuration>
</configuration>

一些配置节点说明(水平有限就不翻译了,直接贴书上的表格):

Property name Description
connection.provider Provider class to open and close database
connections.
connection.driver_class This is specific to the RDBMS used, and is typically set
by the dialect.
connection.connection_string Database connection string.
connection.connection_string_
name
Name of connection string in
<connectionStrings> element.
connection.isolation Transaction isolation level.
dialect Required. A class to build RDBMS-specific SQL strings.
Typically, this is one of the many dialects from the
NHibernate.Dialect namespace
show_sql Boolean value. Set to true to log all SQL statements to
Console.Out. Alternatively, log4net may be used to
log to other locations
current_session_context_class Class to manage contextual sessions
query.substitutions Comma-separated list of translations to perform on
query strings. For example, True=1, Yes=1, False=0,
No=0.
sql_exception_converter Class to convert RDBMS-specific ADO.NET Exceptions
to custom exceptions
prepare_sql Boolean value. Prepares SQL statements and caches
the execution plan for the duration of the database
connection.
command_timeout Number of seconds to wait for a SQL command to
complete before timing out.
adonet.batch_size Number of SQL commands to send at once before
waiting for a response from the database
generate_statistics Enables tracking of some statistical information,
such as the number of queries executed and entities
loaded
proxyfactory.factory_class Required. Specifies a factory class for our chosen
proxy framework, in this case Castle DynamicProxy2
format_sql Adds line endings for easier-to-read SQL statements

顺便贴一下Nhibernate的数据访问架构:

将hibernate-configuration配置在单独的文件中

我们也可以将App.config中的hibernate-configuration节点抽取出来,单独配置在另一个XML文件中,并将该XML文件的属性,复制到输出目录设置为:如果较新复制。

利用代码配置hibernate-configuration

我们也可以通过代码来配置hibernate-configuration节点中的内容.

App.config文件还是要的:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="db" connectionString="Server=.\SQLExpress;
Database=NHCookbook; Trusted_Connection=SSPI"/>
</connectionStrings>
</configuration>

然后在Program.cs代码中先引用命名空间:

using NHibernate.ByteCode.Castle;
using NHibernate.Cfg;
using NHibernate.Cfg.Loquacious;
using NHibernate.Dialect;

在Main方法中增加如下代码:

var nhConfig = new Configuration()
.Proxy(proxy =>
proxy.ProxyFactoryFactory<ProxyFactoryFactory>())
.DataBaseIntegration(db =>
{
db.Dialect<MsSql2008Dialect>();
db.ConnectionStringName = "db";
db.BatchSize = 100;
})
.AddAssembly("Eg.Core");
var sessionFactory = nhConfig.BuildSessionFactory();
Console.WriteLine("NHibernate Configured!");
Console.ReadKey();

注意:DataBaseIntegration是一个扩展方法,要引用NHibernate.Cfg.Loquacious命名空间。

利用Fluent NHibernate

App.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="db" connectionString="Server=.\SQLExpress;
Database=NHCookbook; Trusted_Connection=SSPI"/>
  </connectionStrings>
</configuration>

增加代码:

using Eg.FluentMappings.Mappings;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate.ByteCode.Castle;
var nhConfig = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008
.ConnectionString(connstr =>
connstr.FromConnectionStringWithKey("db")
)
.ProxyFactoryFactory<ProxyFactoryFactory>()
.AdoNetBatchSize(100)
)
.Mappings(mappings => mappings.FluentMappings
.AddFromAssemblyOf<ProductMapping>()
)
.BuildConfiguration();
var sessionFactory = nhConfig.BuildSessionFactory();
Console.WriteLine("NHibernate configured fluently!");
Console.ReadKey();

利用ConfORM Mappings

App.config:

View Code
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="hibernate-configuration"
    type="NHibernate.Cfg.ConfigurationSectionHandler,
NHibernate"/>
  </configSections>
  <connectionStrings>
    <add name="db" connectionString="Server=.\SQLExpress;
Database=NHCookbook; Trusted_Connection=SSPI"/>
  </connectionStrings>
  <hibernate-configuration
  xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
      <property name="proxyfactory.factory_class">
        NHibernate.ByteCode.Castle.ProxyFactoryFactory,
        NHibernate.ByteCode.Castle
      </property>
      <property name="dialect">
        NHibernate.Dialect.MsSql2008Dialect,
        NHibernate
      </property>
      <property name="connection.connection_string_name">
        db
      </property>
      <property name="adonet.batch_size">
        100
      </property>
    </session-factory>
  </hibernate-configuration>
</configuration>

增加代码:

using Eg.ConfORMMapping.Mappings;
using NHibernate.Cfg;
var mappingFactory = new MappingFactory();
var mapping = mappingFactory.CreateMapping();
var nhConfig = new Configuration().Configure();
nhConfig.AddDeserializedMapping(mapping, null);
var sessionFactory = nhConfig.BuildSessionFactory();
Console.WriteLine("NHibernate configured!");
Console.ReadKey();
原文地址:https://www.cnblogs.com/Gyoung/p/2510937.html