Configuring NHibernate with hibernate.cfg.xml
使用hibernate.cfg.xml配置NHibernate
配置NHibernate的另一个常用方法是使用一个单独的XML配置文件.本节将介绍如何使用hibernate.cfg.xml来实现上节中的NHibernate配置.
准备工作
1. 完成第一章中Eg.Core项目的模式和映射部分.
2. 在你的解决方案中添加一个名为ConfigByXML的控制台项目.
3. 将她设置为启动项目.
4. 为该项目添加NHibernate.dll 和NHibernate.ByteCode.Castle.dll引用,这两个文件在Lib文件夹中.
5. 为该项目添加到Eg.Core的引用.
步骤
1. 添加一个App.config文件如下:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
<?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionStrings> <add name="db" connectionString="Server=.\SQLExpress; Database=NHCookbook; Trusted_Connection=SSPI"/> </connectionStrings> </configuration>
2. 添加一个名为hibernate.cfg.xml的XML文件如下:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
<?xml version="1.0" encoding="utf-8" ?> <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>
3. 右击hibernate.cfg.xml文件选择选择【属性】.
4. 将【复制到输出目录】改为【如果较新则复制】.
5. 打开Program.cs为其添加using NHibernate.Cfg;.
6. 在Main函数中添加下面的代码以完成对NHibernate的配置:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
var nhConfig = new Configuration().Configure(); var sessionFactory = nhConfig.BuildSessionFactory(); Console.WriteLine("NHibernate Configured!"); Console.ReadKey();
7. 编译运行,可以看到提示文本NHibernate Configured!.
原理
本节的示例运行原理同上节. 我们仍旧使用了在App.config中定义的db连接字符串.但是,在本节中我们把hibernate-configuration元素节点从App.config文件中移到了hibernate.cfg.xml文件. 在第一章中我们在解决方案中添加了schema文件夹(含nhibernate-configuration.xsd和nhibernate-mapping.xsd文件),因此我们在编写映射文件时会获得自能感知的支持. 改变【复制到输出目录】是为了确保编译时hibernate.cfg.xml文件会被复制到DEBUG目录.
扩展内容
默认情况下,NHibernate会在hibernate.cfg.xml查找她的配置. 然而,我们也可以指定一个另外的配置文件,代码如下:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
var cfgFile = "cookbook.cfg.xml"; var nhConfig = new Configuration().Configure(cfgFile);
此外,还可以将配置文件嵌入到程序集中.这种情况下,我们通过程序集中包含该资源以及该嵌入资源的名字.
最后,我们可以使用XmlReader提供任何其他来源的配置.