子曾经曰过

  博客园  :: 首页  ::  ::  ::  :: 管理

ORM是什么东西?复杂的名字叫对象关系模型。最常用的就是数据库到你的项目里的对象的映射,这样你可以像操作对象一样操作数据库,并且额外的好处是,如果你的语句比较兼容的话,可以更换数据库的时候减少很多工作。

NHibernate,是个什么东西?它其实不是个东西,是ORM在.NET上实现的一个功能性类库。

例子背景:

项目名称 NhibernateSample  数据库MSSQL2005 要用的表Student  字段

 [StudentId] [int] IDENTITY(1,1) NOT NULL,
 [StudentName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
 [StudentPassword] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
 [EmailAddress] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
 [DateCreated] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,

第一步:

既然是个类库,得先下载下来,地址 http://nhforge.org/media/Default.aspx?Sort=Downloads&PageIndex=1,

版本多,这一点也是很麻烦的,很多东西版本太多,有时候选择多了反而不是好事。下载后得到 NHibernate-3.0.0.GA-bin.rar

最简单的办法就是把所有 .dll 都拷贝到你的bin文件里然后添加它们的引用,这就完成了对NHibernate使用的第一步。

第二步:写个Nhibernate连接数据库的XML文件hibernate.cfg.xml放到bin目录里,为什么是hibernate.cfg.xml这个名字呢?看啊,

NHibernate.Cfg.Configuration mCfg = new NHibernate.Cfg.Configuration().Configure();如果没这个文件这句会报错,说找不到hibernate.cfg.xml这个文件,那么为什么非要是这个名字呢?VS2008里右键点Configure[从元数据]得到

public const string DefaultHibernateCfgFileName = "hibernate.cfg.xml";
public const string MappingSchemaXMLNS = "urn:nhibernate-mapping-2.2";看见了吧,人家默认的给你定好了,有现成的就用现成的,只要好用。

hibernate.cfg.xml内容

View Code
<?xml version="1.0" encoding="utf-8" ?>
<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=sa
</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>
<property name='proxyfactory.factory_class'>NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
<mapping assembly="NhibernateSample"/>
</session-factory>
</hibernate-configuration>

注意这个config文件里的配置节点 xmlns="urn:nhibernate-configuration-2.2" ,人家也给你配好了,不能改成别的,和刚才那个名字一样,这就是配置文件的麻烦,很麻烦。

第三步:写表里字段的映射文件Student.cs和Student.hbm.xml,这两个文件可以用CodeSmith调用NHibernate模板生成,不过生成还得根据需要再改改。

Student.cs

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace NhibernateSample
{
public class Student
{
public Student() { }

private int studentId;
private string studentName;
private string studentPassword;
private string emailAddress;
private string dateCreated;

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 string DateCreated
{
get { return dateCreated; }
set { dateCreated = value; }
}
}

}

Student.hbm.xml

View Code
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="NhibernateSample.Student, NhibernateSample" 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="String" length="100"/>
</class>
</hibernate-mapping>

第四步:简单调用

Dal.cs

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NHibernate;

namespace NhibernateSample
{
public class Dal
{
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";
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
= "代替时间";
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
}
}

}
posted on 2011-02-15 23:03  人的本质是什么?  阅读(363)  评论(0编辑  收藏  举报