<add key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver" />
<add key="hibernate.connection.connection_string" value="Server=localhost;initial catalog=nhibernate;User ID=someuser;Password=somepwd;Min Pool Size=2" />
</nhibernate>
</configuration>
上面的例子中使用SqlClient驱动,连接到本地的nhibernate数据库,并且使用提供的用户和密码.还会有其他的配置项,你可以参看文档.
步骤5:开始体验NHibernate的神奇
所有艰苦的工作已经做完了.如果所有的工作完成后,你将会有这些成果:
æ User.cs - 需要持久化的.Net类.
æ User.hbm.xml - 映射文件
æ app.config - 带有Ado.net连接信息的配置文件(你也可以在代码中指定的)
æ 一个叫做user的数据库表.
在代码里面使用NHibernate是很简单的事情:
1. 创建一个Configuration对象.
2. 告诉Configuration你想要持久化哪一种对象.
3. 创建一个Session连接到你设定的数据库.
4. 载入,保存和查询你的对象.
5. Flush()你的Session
好,让我们来看看一些代码:
创建一个Configuration对象....
Configuration对象知道所有在.Net类和后端数据库之间的映射关系,
Configuration cfg = new Configuration();
cfg.AddAssembly("NHibernate.Demo.QuickStart");
Configuration对象会查找这个Assembly中所有以.hbm.xml结尾的文件.也有其他的方法添加映射文件,这个可能是最简单的一个.
创建一个Session对象.......
ISession对象代表着一个到后端数据库连接,ITransaction代表一个NHibernate管理的事务(Transaction).
ISessionFactory factory = cfg.BuildSessionFactory();
ISession session = factory.OpenSession();
ITransaction transaction = session.BeginTransaction();
载入,保存和查询你的对象......
现在你可以以.net的方式对待这些对象.想在数据库中保存一个新的user?只需要:
User newUser = new User();
newUser.Id = "joe_cool";
newUser.UserName = "Joseph Cool";
newUser.Password = "abc123";
newUser.EmailAddress = "joe@cool.com";
newUser.LastLogon = DateTime.Now;
// Tell NHibernate that this object should be saved
session.Save(newUser);
// commit all of the changes to the DB and close the ISession
transaction.Commit();
session.Close();
这就是NH的好处,大部分时间内你只用关心你的业务对象(BO).
假如你需要根据已经知道的user ID查询一个对象,如果session是open的,你只需要一行:
// open another session to retrieve the just inserted user