在开始前:
下载Nhibernate,官方网站:https://www.hibernate.org/343.html,将下载的文件解压在本地目录,里面包含了必需的dll文件和XML文件的样例等。新建解决方案如下:
lib:必须的dll,可在下载的文件夹中找到
Client:测试用,为启动项目(zzy.db 为数据库文件)
domain:实体类和相应的映射文件
HbernateHelper:用来获取Session
具体步骤如下:
1,新建数据库表TB_PERSON如下:
其中ID为整形主键,自动增长
2,新建Nhibernate的配置文件hibernate.cfg.xml如下:
Code
<?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.
-->
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<session-factory name="NHibernate.Test">
<property name="connection.driver_class">NHibernate.Driver.SQLite20Driver</property>
<property name="connection.connection_string">
Data Source=zzy.db;Version=3
</property>
<property name="dialect">NHibernate.Dialect.SQLiteDialect</property>
<property name="query.substitutions">true=1;false=0</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
<mapping assembly="Domain"/>
</session-factory>
</hibernate-configuration>
该配置文件可以在下载的Nhibernat压缩文件中找到模板。
3,新建实体及映射文件
其中Person类代码如下:
Code
using System;
using System.Collections.Generic;
using System.Text;
namespace Domain.Entities
{
public class Person
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual int Age { get; set; }
}
}
对应的映射文件Person.hbm.xml如下:
Code
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="Domain"
namespace="Domain.Entities">
<class name ="Person" table="TB_PERSON">
<id name="Id" column ="ID">
<generator class ="native"/>
</id>
<property name ="Name"/>
<property name ="Age"/>
</class>
</hibernate-mapping>
该映射文件也可在下载的Nhibernate压缩文件中找到模板。
4,获取Session
在HbernateHelper下新建类:Helper,代码如下:
Code
using System;
using System.Collections.Generic;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
namespace HbernateHelper
{
public class Helper
{
private static ISessionFactory _factory;
private static ISessionFactory GetFactory()
{
if (_factory == null)
{
_factory = new Configuration().Configure().BuildSessionFactory();
}
return _factory;
}
public static ISession GetSession()
{
return GetFactory().OpenSession();
}
}
}
5,在主项目中测试结果
Code
using System;
using System.Collections.Generic;
using System.Text;
using HbernateHelper;
using NHibernate;
using Domain.Entities;
namespace Fuck
{
class Program
{
static void Main(string[] args)
{
ISession session = Helper.GetSession();
Person person = new Person();
person.Name = "zzy";
person.Age = 24;
session.SaveOrUpdate(person);
session.Flush();
session.Close();
session = Helper.GetSession();
Person anotherPerson = (Person)session.Get<Person>(1);
Console.Write(anotherPerson.Name + " AGE:" + anotherPerson.Age.ToString());
Console.Read();
session.Flush();
session.Close();
}
}
}
测试代码中包含一个简单的新建和查询操作,需要注意:别忘了把必要的dll引用加上。
这就是全部。