1.獲取NHibernate
首先到 http://www.nhforge.org/下載NHibernate的最新版本,本示例的NHibernate版本爲官方2008年9月29日最新發布的NHibernate-2.0.1.GA版本.
2.建數據庫,建表
Create Database Nhibernate
Go
Use Nhibernate
Go
Create table Users
(
Id int primary key identity(1,1),
[Name] varchar(100),
Email varchar(100),
Password varchar(100)
)
Go
SELECT * FROM Users
3.代碼編寫
打開 Visual Studio 2005 新建 WebApplication,命名爲NHibernateSample,添加相關DLL的引用。
新建model文件夾,在該文件夾下建User類,代碼如下:
using System;
namespace NHibernateSample.model
{
public class User
{
public int id;
public int Id
{
get { return id; }
set { id = value; }
}
public string name;
public string Name
{
get { return name; }
set { name = value; }
}
public string email;
public string Email
{
get { return email; }
set { email = value; }
}
public string password;
public string Password
{
get { return password; }
set { password = value; }
}
}
}
在model文件夾下新建User.hbm.xml,設置屬性中生成操作爲"嵌入的資源",輸入以下內容:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="NHibernateSample.model.User,NHibernateSample" table="Users" lazy="false">
<id name="Id" column="Id" type="Int32">
<generator class="native"></generator>
</id>
<property name="Name" column="Name" type="String" length="100"></property>
<property name="Email" column="Email" type="String" length="100"></property>
<property name="Password" column="Password" type="String" length="100"></property>
</class>
</hibernate-mapping>
在根目錄下建立hibernate.cfg.xml文件,設置屬性中生成操作爲"嵌入的資源",輸入以下內容:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<session-factory name="NHibernateSample">
<!-- properties -->
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Server=yangchun;initial catalog=NHibernate;uid=sa;pwd=sql;</property>
<property name="show_sql">false</property>
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
<property name="use_outer_join">true</property>
<!-- mapping files -->
<mapping assembly="NHibernateSample" />
</session-factory>
</hibernate-configuration>
在頁面編寫如下代碼:
1.插入數據:
protected void btnSave_Click(object sender, EventArgs e)
{
NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration().Configure(Server.MapPath("~/hibernate.cfg.xml"));
NHibernate.ISession session = cfg.BuildSessionFactory().OpenSession();
NHibernate.ITransaction transaction = session.BeginTransaction();
NHibernateSample.model.User user = new NHibernateSample.model.User();
try
{
user.Name = txtName.Text;
user.Email = txtEmail.Text;
user.Password = txtPassword.Text;
session.Save(user);
transaction.Commit();
RegisterStartupScript("alert", "<script>alert('保存成功!');</script>");
}
catch (Exception ex)
{
transaction.Rollback();
RegisterStartupScript("alert", "<script>alert('保存失敗!錯誤信息如下:" + ex.Message + "');</script>");
}
finally
{
session.Close();
}
}
2.查詢數據
private void LoadInfo( int Id)
{
NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration().Configure(Server.MapPath("~/hibernate.cfg.xml"));
NHibernate.ISession session = cfg.BuildSessionFactory().OpenSession();
NHibernateSample.model.User user = new NHibernateSample.model.User();
user = (NHibernateSample.model.User)session.Load(typeof(NHibernateSample.model.User), Id);
txtId.Text = user.Id.ToString();
txtName.Text = user.Name;
txtEmail.Text = user.Email;
txtPassword.Text = user.Password;
}
3.查詢全部數據:
private void Load()
{
NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration().Configure(Server.MapPath("~/hibernate.cfg.xml"));
NHibernate.ISession session = cfg.BuildSessionFactory().OpenSession();
grdItems.DataSource = session.CreateQuery("select u from User as u").List();
grdItems.DataBind();
session.Close();
}
4.修改數據:
protected void btnSave_Click(object sender, EventArgs e)
{
NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration().Configure(Server.MapPath("~/hibernate.cfg.xml"));
NHibernate.ISession session = cfg.BuildSessionFactory().OpenSession();
NHibernate.ITransaction transaction = session.BeginTransaction();
NHibernateSample.model.User user = new NHibernateSample.model.User();
try
{
user.Id = Convert.ToInt32(txtId.Text.Trim());
user.Name = txtName.Text;
user.Email = txtEmail.Text;
user.Password = txtPassword.Text;
session.Update(user);
transaction.Commit();
RegisterStartupScript("alert", "<script>alert('修改成功!');</script>");
}
catch (Exception ex)
{
transaction.Rollback();
RegisterStartupScript("alert", "<script>alert('修改失敗!錯誤信息如下:" + ex.Message + "');</script>");
}
finally
{
session.Close();
}
}
5.刪除數據:
protected void grdItems_DeleteCommand(object source, DataGridCommandEventArgs e)
{
NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration().Configure(Server.MapPath("~/hibernate.cfg.xml"));
NHibernate.ISession session = cfg.BuildSessionFactory().OpenSession();
NHibernate.ITransaction transcation = session.BeginTransaction();
try
{
NHibernateSample.model.User user = new NHibernateSample.model.User();
user.Id = Convert.ToInt32(e.Item.Cells[0].Text.Trim());
session.Delete(user);
transcation.Commit();
RegisterStartupScript("alert", "<script>alert('刪除成功!');</script>");
Load();
}
catch (Exception ex)
{
transcation.Rollback();
RegisterStartupScript("alert", "<script>alert('刪除失敗!錯誤信息如下:" + ex.Message + "');</script>");
}
finally
{
session.Close();
}
}
目前初學,寫的不對或者不好的請見諒!
本文轉載自:http://www.cnblogs.com/88223100/archive/2009/01/18/1354943.html