NHibernate数据库映射教程:1、NHibernate实例入门(2)
(五) 创建辅助类NHBHelper
在SelfTest2类库中添加类:NHBHelper
用于从ISessionFactory中获取一个ISession(NHibernate的工作单元),如下:
public class NHBHelper
{
private ISessionFactory _sessionFactory;
public NHBHelper()
{
_sessionFactory = GetSessionFactory();
}
private ISessionFactory GetSessionFactory()
{
return (new Configuration()).Configure("NHibernate.cfg.xml").BuildSessionFactory();
}
public ISession GetSession()
{
return _sessionFactory.OpenSession();
}
}
这里所用到的名字空间为:
using NHibernate.Cfg;
using NHibernate;
在这个类库中添加引用:NHibernate.dll(从本解决方案中的另一个类库中选择)
这里一起把用到的库引入好了:
(六) 添加NHibernate配置文件
文件名为:hibernate.cfg.xml(因为辅助类NHBHelper中要读取这个文件,我把这个文件放到了bindebug中(注意路径))
因为现在用的是mssql2000,所以从
NHibernate-2.1.1.GA-srcsrcNHibernate.Config.Templates
找到MSSQL.cfg.xml文件,改改
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property>NHibernate.Driver.SqlClientDriver</property>
<property>Server=.;initial catalog=selftest;uid=sa;pwd=***;</property>
<property>NHibernate.Dialect.MsSql2000Dialect</property>
<property>NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
<mapping assembly="SelfTest2"/>
</session-factory>
</hibernate-configuration>
这里有几点注意:
(1)数据库连接串
(2)代理属性这里<property>NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
现在这里用的是Castle代理,所以库要添加对
NHibernate.ByteCode.Castle.dll
的引用。否则会出现异常。
贴出castle代理的session-factory最简配置:
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<session-factory>
<property>NHibernate.Driver.SqlClientDriver</property>
<property>NHibernate.Dialect.MsSql2005Dialect</property>
<property>
Server=(local);initial catalog=nhibernate;Integrated Security=SSPI
</property>
<property>NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
</session-factory>
</hibernate-configuration>
可以参考:
http://nhforge.org/blogs/nhibernate/archive/2008/11/09/nh2-1-0-bytecode-providers.aspx
(3) 一定要添加<mapping assembly="SelfTest2"/>节。
(七)添加操作类NHBDo
用于业务逻辑,在本类库添加新类NHBDo.cs
public class NHBDo
{
protected ISession Session { get; set; }
public NHBDo(ISession session)
{
Session = session;
}
public void CreateCustomer(Customer customer)
{
Session.Save(customer);
Session.Flush();
}
public Customer GetCustomerById(int customerId)
{
return Session.Get<Customer>(customerId);
}
}
名字空间添加:
using NHibernate;
(八) 添加测试Test
在本类库添加新类Test.cs
用于测试。
[TestFixture]
public class Test
{
NHBDo ddo;
NHBHelper helper;
[TestFixtureSetUp]
public void Create()
{
helper = new NHBHelper();
ddo = new NHBDo(helper.GetSession());
}
[Test]
public void TestGetOne()
{
Customer customer=ddo.GetCustomerById(1);
string s=customer.FirstName;
//Assert.AreEqual(1, customerId);
}
}