内容摘要
准备工作
开发流程
程序开发
一、准备工作
1.1开发环境
开发工具:VS2008以上,我使用的是VS2010
数据库:任意关系型数据库,我使用的是SQL Server 2005 Express
1.2测试环境
nunit 2.5.7
二、开发流程
NHibernate程序的开发流程是:
(1).编写领域类与映射文件
(2).使用NHibernate工具生成对应的数据库结构
(3).编写DAO(数据库访问对象)
(4).使用NUnit测试DAO(数据访问对象)的增、删、该、查方法
三、程序开发
3.1 建立Domain项目,如图3.1.1所示。
图3.1.1
编写类文件Product.cs
Product
/// <summary>
/// 商品
/// </summary>
public class Product
{
/// <summary>
/// ID
/// </summary>
public virtual Guid ID { get; set; }
/// <summary>
/// 编号
/// </summary>
public virtual string Code { get; set; }
/// <summary>
/// 名称
/// </summary>
public virtual string Name { get; set; }
/// <summary>
/// 规格
/// </summary>
public virtual string QuantityPerUnit { get; set; }
/// <summary>
/// 单位
/// </summary>
public virtual string Unit { get; set; }
/// <summary>
/// 售价
/// </summary>
public virtual decimal SellPrice { get; set; }
/// <summary>
/// 进价
/// </summary>
public virtual decimal BuyPrice { get; set; }
/// <summary>
/// 备注
/// </summary>
public virtual string Remark { get; set; }
}
编写映射文件Product.hbm.xml
Product.hbm.xml
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Domain" namespace="Domain">
<class name="Product" table="T_Product" lazy="true" >
<id name="ID" column="ID" type="Guid" >
<generator class="assigned" />
</id>
<property name="Code" type="string">
<column name="Code" length="50"/>
</property>
<property name="Name" type="string">
<column name="Name" length="50"/>
</property>
<property name="QuantityPerUnit" type="string">
<column name="QuantityPerUnit" length="50"/>
</property>
<property name="Unit" type="string">
<column name="Unit" length="50"/>
</property>
<property name="SellPrice" type="decimal">
<column name="SellPrice" precision="14" scale="2"/>
</property>
<property name="BuyPrice" type="decimal">
<column name="BuyPrice" precision="14" scale="2"/>
</property>
<property name="Remark" type="string">
<column name="Remark" length="200"/>
</property>
</class>
</hibernate-mapping>
然后,将映射文件“Product.hbm.xml”的属性“生成方式”设置为“嵌入的资源”,如图3.1.2所示。
图3.1.2
3.2 建立名为“NHibernateTest”的项目,如图3.2.1所示
图3.2.1
引用程序集“Antlr3.Runtime.dll”,“Iesi.Collections.dll”,“NHibernate.dll”,“Remotion.Data.Linq.dll”,“nunit.framework.dll”,如图3.2.2所示
图3.2.2
然后音乐Domain项目,复制并粘贴NHibernate的配置模板到项目中,如图3.2.3所示
图3.2.3
修改该文件的属性为“始终复制”
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!--
This template was written to work with NHibernate.Test.
Copy the template to your NHibernate.Test project folder and rename it in hibernate.cfg.xml and change it
for your own use before compile tests in VisualStudio.
-->
<!-- This is the System.Data.dll provider for SQL Server -->
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<session-factory name="NHibernateTest">
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">
server=.\SQLEXPRESS;database=NHibernateDemo;uid=sa;pwd=;
</property>
<property name="adonet.batch_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
<property name="use_outer_join">true</property>
<property name="command_timeout">60</property>
<property name="hbm2ddl.auto">update</property>
<property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
<mapping assembly="Domain"/>
</session-factory>
</hibernate-configuration>
创建“NHibernateInit.cs”类文件,用于初始化数据库的表结构
NHibernateInit.cs
[TestFixture]
public class NHibernateInit
{
[Test]
public void InitTest()
{
var cfg = new NHibernate.Cfg.Configuration().Configure("Config/hibernate.cfg.xml");
using (ISessionFactory sessionFactory = cfg.BuildSessionFactory()) { }
}
}
复制proxyfactory类的程序集“LinFu.DynamicProxy.dll”和“NHibernate.ByteCode.LinFu.dll”到项目中,并修改生成方式,如图3.2.4所示
图3.2.4
设置项目属性的启动操作,为“启动外部程序”,然后选择NUnit应用程序的路径。如图3.2.5所示。
图3.2.5
打开SQL Server Management Studio Express,创建名为“NHibernateDemo”的数据库,如图3.2.6
图3.2.6
启用NUnit,选择名称“NHibernateTest.dll”的程序集。如图3.2.7所示。接着,点击“run”按钮运行NUnit。
图3.2.7
这时,我们再打开数据库,就会发现,NHibernate已经为我们建立了“T_Product”表,如图3.2.8所示。
图3.2.8
3.3 编写DAO(数据库访问对象),建立名为“Dao”的项目。如图3.3.1所示。
图3.3.1
引用项目所需的程序集,接着编写IProductDao接口和 ProductDao类
ProductDao
public interface IProductDao
{
object Save(Product entity);
void Update(Product entity);
void Delete(Product entity);
Product Get(object id);
Product Load(object id);
IList<Product> LoadAll();
}
public class ProductDao : IProductDao
{
private ISessionFactory sessionFactory;
public ProductDao()
{
var cfg = new NHibernate.Cfg.Configuration().Configure("Config/hibernate.cfg.xml");
sessionFactory = cfg.BuildSessionFactory();
}
public object Save(Domain.Product entity)
{
using (ISession session = sessionFactory.OpenSession())
{
var id = session.Save(entity);
session.Flush();
return id;
}
}
public void Update(Domain.Product entity)
{
using (ISession session = sessionFactory.OpenSession())
{
session.Update(entity);
session.Flush();
}
}
public void Delete(Domain.Product entity)
{
using (ISession session = sessionFactory.OpenSession())
{
session.Delete(entity);
session.Flush();
}
}
public Domain.Product Get(object id)
{
using (ISession session = sessionFactory.OpenSession())
{
return session.Get<Domain.Product>(id);
}
}
public Domain.Product Load(object id)
{
using (ISession session = sessionFactory.OpenSession())
{
return session.Load<Domain.Product>(id);
}
}
public IList<Domain.Product> LoadAll()
{
using (ISession session = sessionFactory.OpenSession())
{
return session.Query<Domain.Product>().ToList();
}
}
}
然后在测试项目“NHibernateTest”中编写测试类“ProductDaoTest”。
ProductDaoTest
[TestFixture]
public class ProductDaoTest
{
private IProductDao productDao;
[SetUp]
public void Init()
{
productDao = new ProductDao();
}
[Test]
public void SaveTest()
{
var product = new Domain.Product
{
ID = Guid.NewGuid(),
BuyPrice = 10M,
Code = "ABC123",
Name = "电脑",
QuantityPerUnit = "20x1",
SellPrice = 11M,
Unit = "台"
};
var obj = this.productDao.Save(product);
Assert.NotNull(obj);
}
[Test]
public void UpdateTest()
{
var product = this.productDao.LoadAll().FirstOrDefault();
Assert.NotNull(product);
product.SellPrice = 12M;
Assert.AreEqual(12M, product.SellPrice);
}
[Test]
public void DeleteTest()
{
var product = this.productDao.LoadAll().FirstOrDefault();
Assert.NotNull(product);
var id = product.ID;
this.productDao.Delete(product);
Assert.Null(this.productDao.Get(id));
}
[Test]
public void GetTest()
{
var product = this.productDao.LoadAll().FirstOrDefault();
Assert.NotNull(product);
var id = product.ID;
Assert.NotNull(this.productDao.Get(id));
}
[Test]
public void LoadTest()
{
var product = this.productDao.LoadAll().FirstOrDefault();
Assert.NotNull(product);
var id = product.ID;
Assert.NotNull(this.productDao.Get(id));
}
[Test]
public void LoadAllTest()
{
var count = this.productDao.LoadAll().Count;
Assert.True(count > 0);
}
}
最后运行NUnit测试该项目。效果如图3.3.2所示。
图3.3.2
好了,一个NHibernate完整的项目就做完了。从中我们可以发现,此应用程序项目没有编写一条SQL语句,就能实现数据的增、删、该、查。
这样一来,便简化了我们的项目开发。O(∩_∩)O~