NHibernate使用入门示例
NHibernate使用入门
环境:
VS2008 SP1,NHibernate 2.1 Beta2
1.新建Web工程WebApplication1
2.在Default.aspx页加入按钮Button1
3.按钮click书写如下代码:
//通过配置文件建立 Nhibernate 环境,其中当前目录下的文件hibernate.cfg.xml为配置文件
Configuration cfg = new Configuration();
cfg.Configure(Server.MapPath("~")+"hibernate.cfg.xml");
ISessionFactory _SessionFactory = cfg.BuildSessionFactory();//建立Session工厂
ISession session = _SessionFactory.OpenSession();//打开Session
//Product为领域对象
Product p = new Product();
p.Name = "Name";
p.Category = "Category";
//持久化领域对象
session.SaveOrUpdate(p);
session.Flush();
//Session关闭
session.Close();
session.Dispose();
session = null;
4.建立领域对象文件Product.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication1
{
public class Product
{
public virtual Int32 ID{get;set;}
public virtual String Name{get;set;}
public virtual String Category{get;set;}
}
}
5.编写领域对象映射文件
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="WebApplication1.Product, WebApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" table="Product" xmlns="urn:nhibernate-mapping-2.2">
<id name="ID" type="Int32" unsaved-value="0" column="ID">
<generator class="identity" />
</id>
<property name="Name" type="String">
<column name="Name" length="50" not-null="true"/>
</property>
<property name="Category" type="String">
<column name="Category" length="50" not-null="true"/>
</property>
</class>
</hibernate-mapping>
6.编写配置文件hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<!-- properties -->
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Data Source=127.0.0.1;Database=OA;UID=pc;pwd=1</property>
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
<property name="show_sql">true </property>
<property name="use_outer_join">true</property>
<property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
<!-- 代理工厂,可以使用Castle,也可以使用LinFu -->
<!-- <property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>-->
<property name='proxyfactory.factory_class'>NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
<!-- mapping files 领域对象映射文件所在程序集 -->
<mapping assembly="WebApplication1"/>
</session-factory>
</hibernate-configuration>
7.直接运行项目并点击 Button1.