1.为系统引入NHibernate的库,并且配置NHibernate;
2.新建一个将要持久化.Net对象的表;
3.构建一个需要被持久化的.Net类;
4.构建一个可以让NHibernate知道如何完成ORM映射的XML文件;
5.使用NHibernate的API来编程
我下载的nhibernate(http://www.nhibernate.org/)版本是2.0.1的,使用的配置是: sqlser2000+nhibernate2.1.0+vs2008
nhibernate配置教程 收藏
前几天在看petshop4的pdf详解文档,作者说如果这个架构再加上orm,那就prefect了,当时就对orm很感兴趣了,就上网找了点资料了解下,准备对nhibernate入门了。
经过2天的闷头奋战,终于入门了,累啊,发现查了网上很多资料都不是很详细入门教程,怎么都调试不过去,不过后来还是给我瞎搞八搞给弄出来了,赶紧记下来。
1.为系统引入NHibernate的库,并且配置NHibernate;
2.新建一个将要持久化.Net对象的表;
3.构建一个需要被持久化的.Net类;
4.构建一个可以让NHibernate知道如何完成ORM映射的XML文件;
5.使用NHibernate的API来编程
我下载的nhibernate(http://www.nhibernate.org/)版本是2.0.1的,使用的配置是: sqlser2000+nhibernate2.1.0+vs2008
一、新建一个web项目,命名为Webapplication1,然后把下载的nhibernate添加到项目中(Castle.Core.dll,Castle.DynamicProxy2.dll,Iesi.Collections.dll,log4net.dll,NHibernate.dll)
二、在数据库里面新建一个数据库NHibernateSample,新建一张表Student


[ StudentId ] [ int ] IDENTITY ( 1 , 1 ) NOT NULL ,
[ StudentName ] [ nvarchar ] ( 40 ) COLLATE Chinese_PRC_CI_AS NULL ,
[ StudentPassword ] [ nvarchar ] ( 20 ) COLLATE Chinese_PRC_CI_AS NULL ,
[ EmailAddress ] [ nvarchar ] ( 40 ) COLLATE Chinese_PRC_CI_AS NULL ,
[ DateCreated ] [ datetime ] NULL
)
三、新建一个持久化类Student.cs文件


{
public Student() { }
private int studentId;
private string studentName;
private string studentPassword;
private string emailAddress;
private DateTime dateCreated;
private ISet courses = new HashedSet();
public virtual int StudentId
{
get { return studentId; }
set { studentId = value; }
}
public virtual string StudentName
{
get { return studentName; }
set { studentName = value; }
}
public virtual string StudentPassword
{
get { return studentPassword; }
set { studentPassword = value; }
}
public virtual string EmailAddress
{
get { return emailAddress; }
set { emailAddress = value; }
}
public virtual DateTime DateCreated
{
get { return dateCreated; }
set { dateCreated = value; }
}
public virtual ISet Courses
{
get { return courses; }
set { courses = value; }
}
}
virtual方法是要加上去的,不然会报错:The following types may not be used as proxies
然后再新建一个Student.hbm.xml映射文件,这个映射文件也可以用软件自动生成,这样就不用自己编写了。


< hibernate-mapping xmlns ="urn:nhibernate-mapping-2.2" >
< class name ="WebApplication1.Student, WebApplication1" table ="Student" >
< id name ="StudentId" column ="StudentId" type ="Int32" >
< generator class ="native" />
</ id >
< property name ="StudentName" column = "StudentName" type ="string" length ="40" />
< property name ="StudentPassword" type ="string" length ="20" />
< property name ="EmailAddress" type ="String" length ="40" />
< property name ="DateCreated" type ="DateTime" length ="8" />
< set name ="Courses" table ="StudentCourse" inverse ="false" >
< key column ="StudentID" />
< many-to-many column ="CourseID" class =" WebApplication1.Course, WebApplication1 " />
</ set >
</ class >
</ hibernate-mapping >
<class name="WebApplication1.Student, WebApplication1" table="Student">
这个不要搞错,根据自己的项目程序集命名
这个xml文件建好之后还要把它设为嵌入的资源,不然会报错:in expected: <end-of-text>
设置方法:右击文件-属性-生成操作选项里面改成‘嵌入的资源’
四、创建一个配置文件,这个配置文件一共有3种写法
1:在web.config,App.config里面配置
则需要这样实例化Configuration对象。
NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
这种配置方法将会到应用程序配置文件(App.Config,Web.Config)中查找NHibernate的配置信息
2:hibernate.cfg.xml
建立名为hibernate.cfg.xml的文件。实例化Configuration config = new Configuration().Configure();这样NHibernate将会在目录下自动寻找hibernate.cfg.xml的配置文件。文件创建在bin文件夹下面
hibernate.cfg.xml的格式


< hibernate-configuration xmlns ="urn:nhibernate-configuration-2.2" >
< session-factory >
< property name ="connection.driver_class" > NHibernate.Driver.SqlClientDriver </ property >
< property name ="connection.connection_string" >
Data Source=.;Initial Catalog=NHibernateSample;Persist Security Info=True;User ID=sa;Password=11
</ property >
< property name ="adonet.batch_size" > 10 </ property >
< property name ="show_sql" > true </ property >
< property name ="dialect" > NHibernate.Dialect.MsSql2000Dialect </ property >
< property name ="use_outer_join" > true </ property >
< property name ="command_timeout" > 10 </ property >
< property name ="query.substitutions" > true 1, false 0, yes 'Y', no 'N' </ property >
< mapping assembly ="WebApplication1" />
</ session-factory >
</ hibernate-configuration >
注意更改数据库名称和密码
3:直接用程序指明配置信息,比较繁琐,不提倡
我采用的是第二种方法,直接在bin文件夹下面创建hibernate.cfg.xml文件。
五、开始用nhibernate来进行操作数据库了,新建Dal.cs类,


{
public void testData()
{
NHibernate.Cfg.Configuration mCfg = new NHibernate.Cfg.Configuration().Configure();
NHibernate.ISessionFactory SessionFactory = null ;
SessionFactory = mCfg.BuildSessionFactory();
ISession vSession = SessionFactory.OpenSession();
#region 查询
string hsql = " from Student where StudentName='kexd' " ;
IQuery query = vSession.CreateQuery(hsql);
// this.dataGridView1.DataSource = query.List<Person>();
IList < Student > list = query.List < Student > ();
if (list.Count > 0 )
{
Student obj = (Student)list[ 0 ];
// .....
}
#endregion
#region 插入
/*
Student stu = new Student();
stu.StudentName = "test22";
stu.StudentPassword = "test22";
stu.EmailAddress = "test22@54job.com";
stu.DateCreated = DateTime.Now;
ITransaction vTransaction = vSession.BeginTransaction();
try
{
vSession.Save(stu);
vTransaction.Commit();
}
catch (Exception)
{
vTransaction.Rollback();
}
vSession.Close();
*/
#endregion
#region 更新
/*
IQuery query = vSession.CreateQuery("from Student where StudentName='kexd'");
IList<Student> list = query.List<Student>();
ITransaction vTransaction = vSession.BeginTransaction();
try
{
foreach (Student stu in list)
{
stu.EmailAddress = "kesfzu@21cn.com";
vSession.Save(stu);
}
vTransaction.Commit();
}
catch (Exception)
{
vTransaction.Rollback();
}
finally
{
vSession.Close();
}
*/
#endregion
#region 删除
/*
IQuery query = vSession.CreateQuery("from Student where StudentName='ffer'");
IList<Student> list = query.List<Student>();
ITransaction vTransaction = vSession.BeginTransaction();
try
{
foreach (Student stu in list)
{
vSession.Delete(stu);
}
vTransaction.Commit();
}
catch (Exception)
{
vTransaction.Rollback();
}
finally
{
vSession.Close();
}
*/
#endregion
}
}
引入2个类库
using NHibernate;
using System.Collections.Generic;
OK,查询,更新,插入,删除操作都有了,要用哪个去掉注释就行了,现在就可以在default.aspx,里面调用testData()方法测试了