NHibernate增删改查示例及代码


1.获取NHibernate

  首先到 http://sourceforge.net/projects/nhibernate/下载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.xygsk.cn/filepages/download.aspx?FileId=File08121410001

posted @ 2008-12-14 22:01  古道轻风  阅读(1680)  评论(7编辑  收藏  举报