• 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

  • 相关阅读:
    BF算法(串模式匹配算法)
    python字符串 常用函数 格式化字符串 字符串替换 制表符 换行符 删除空白 国际货币格式
    python 列表
    python 循环语句
    http://www.pythontutor.com/visualize.html#mode=edit python在线检测代码
    GDI+_绘制QQ头像
    socket编程之select()
    socket编程之select()
    设置itemcontrol的item点击前后不同状态
    设置itemcontrol的item点击前后不同状态
  • 原文地址:https://www.cnblogs.com/88223100/p/1354943.html
Copyright © 2020-2023  润新知