<1>Configuration config = new Configuration();
这种配置方法将会到应用程序配置文件(App.Config,Web.Config)中查找NHibernate的配置信息,NHibernate的配置节必须符合应用程序配置文件个格式:
<? xml version="1.0" encoding="utf-8" ?> < configuration > < configSections > < section name ="nhibernate" type ="System.Configuration.NameValueSectionHandler, System, Version=1.0.3300.0,Culture=neutral, PublicKeyToken=b77a5c561934e089" /> </ configSections > < nhibernate > < add key ="hibernate.connection.provider" value ="NHibernate.Connection.DriverConnectionProvider" /> < add key ="hibernate.dialect" value ="NHibernate.Dialect.MsSql2000Dialect" /> < add key ="hibernate.connection.driver_class" value ="NHibernate.Driver.SqlClientDriver" /> < add key ="hibernate.connection.connection_string" value ="server=.;uid=sa;pwd=19811218;database=loggi ng" /> </ nhibernate > < system .web > // </ system.web > </ configuration ><2>Configuration config = new Configuration().Configure();
这种配置方法将会在应用的相同目录查找名为”hibernate.cfg.xml”的标准Hibernate配置文件,格式如下:
<? xml version="1.0" encoding="utf-8" ?> < hibernate-configuration xmlns ="urn:nhibernate-configuration-2.0" > < session-factory name ="MySessionFactory" > <!-- properties --> < property name ="connection.provider" > NHibernate.Connection.DriverConnectionProvider </ property > < property name ="connection.driver_class" > NHibernate.Driver.SqlClientDriver </ property > < property name ="connection.connection_string" > Server=localhost;initial catalog=Hibernate;Integrated Security=SSPI </ property > < property name ="show_sql" > false </ property > < property name ="dialect" > NHibernate.Dialect.MsSql2000Dialect </ property > < property name ="use_outer_join" > true </ property > < property name ="query.substitutions" > true 1, false 0, yes 'Y', no 'N' </ property > <!-- mapping files --> < mapping assembly ="Test.Model" /> </ session-factory > </ hibernate-configuration ><3>Configuration config = new Configuration().Configure(configFileName);
这种配置方法将查找指定的Hibernate标准配置文件,可以是绝对路径或者相对路径。
<4>另外我们还可以通过编码的方式添加配置信息:
Hashtable props = new Hashtable(); props[“dialect”] = xxxx; // … config.Properties = props;这种方式不够配置文件来的灵活,所以我们一般不建议使用。
------------------------------------------------------------------------------------------- 在取得config后,我们还需要进行映射文件添加,同样,我们常用以下3种不同的方法:
<1>config.AddXmlFile(“Person.hbm.xml”);
<2>config.AddClass(typeof(Test.Model.Person));
<3>config.AddAssembly(“Test.Model”);
以上方法都可以用“阶梯式“的编码风格,如下:
config.AddXmlFile(“Person.hbm.xml”) .AddXmlFile(“User.hbm.xml”) .AddClass( typeof (Test.Model.Customer));
当然,为了方便起见,我们一般把所有的影射类文件及xml文件统一放在一个程序集中,然后使用config.AddAssembly(assemblyName)的方式,让NHibernate自动去查找指定程序集中所有的映射文件和映射类。
你有没有发现在我们使用标准的hibernate配置文件时,有如下一个元素:
<!-- mapping files -->
<mapping assembly="Test.Model" />
对了,你想的不错,我们可以避免在代码中捆绑映射程序集,而在配置文件中指定,这种方式可以说是最灵活的了。
提示:在Web程序中,最好将配置文件改为config的后缀,否则在没有添加对xml的asp.net映射的情况下,你的配置文件就有可能被下载哟!!
转载于:https://www.cnblogs.com/Elong/archive/2007/11/02/946982.html
相关资源:JAVA上百实例源码以及开源项目