NHibernate简单增删改查

Default.aspx.cs    code

 

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using NHibernate;
using NHibernate.Cfg;
using Models;
using System.Collections;


public partial class _Default : System.Web.UI.Page
{
    //定义成员变量
    NHibernate.Cfg.Configuration cfg = null;
    ISessionFactory factory = null;
    ISession session = null;
    ITransaction tran = null;  //事物
    IList list = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.SelectAll();//查找所有信息
        }
    }

    /// <summary>
    /// 公共的内容
    /// </summary>
    public  void PubVod()
    {
        //读取所有配置文件 连接对象
        cfg = new NHibernate.Cfg.Configuration();
        //创建session工厂 负责持久化连接已经or映射
        factory = cfg.Configure().BuildSessionFactory();
        //创建一个可用于用户级别的操作对象 session
        session = factory.OpenSession();

    }

    /// <summary>
    /// 查询的方法
    /// </summary>
    public void SelectAll()
    {
        this.PubVod();
        list = session.Find("from Users");
        this.GridView1.DataSource = list;
        this.GridView1.DataBind();
    }

 
    /// <summary>
    /// 添加数据
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void subBtn_Click(object sender, EventArgs e)
    {
        PubVod();
        //开启事物
        tran = session.BeginTransaction();
        Users users = new Users();// 实例化对象
        users.Name = this.txtName.Text.Trim().ToString();//把文本框的值给对象中的name
        users.Pwd = this.txtPwd.Text.Trim().ToString();
        try
        {
            session.Save(users); //调用session内置的方法
            tran.Commit();//提交事物
            ClientScript.RegisterStartupScript(this.GetType(), "onclick", "<script>alert('添加成功!')</script>");
            this.SelectAll();
        }
        catch (Exception)
        {
            tran.Rollback(); //回滚事物
            //  Response.Write("<script>alert('"+ex.Message+"')</script>");
        }
    }
   
  /// <summaryba
  /// 删除
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        PubVod();
        int id = Convert.ToInt32(this.GridView1.DataKeys[e.RowIndex].Value);
        try
        {
            tran = session.BeginTransaction();
            Users user = session.Load(typeof(Users), id) as Users;
            session.Delete(user);
            tran.Commit();
            this.SelectAll();
        }
        catch (Exception)
        {
             tran.Rollback();
        }
       
      
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        cfg = new NHibernate.Cfg.Configuration();
        factory = cfg.Configure().BuildSessionFactory();
        session = factory.OpenSession(); //打开session

        int id = Convert.ToInt32(this.GridView1.DataKeys[e.RowIndex].Value);
        string name = ((TextBox)this.GridView1.Rows[e.RowIndex].FindControl("TextBox2")).Text.ToString();
        string pwd = ((TextBox)this.GridView1.Rows[e.RowIndex].FindControl("TextBox3")).Text.ToString();

        try
        {
            tran = session.BeginTransaction();
            Users user = session.Load(typeof(Users),id) as Users;
            user.Name = name.ToString();
            user.Pwd = pwd.ToString();
            session.Update(user);
            tran.Commit();
            this.GridView1.EditIndex = -1;
            SelectAll();
        }
        catch (Exception)
        {
            tran.Rollback();
        }
 
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        this.GridView1.EditIndex = e.NewEditIndex;

        SelectAll();
 
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        this.GridView1.EditIndex = -1;
        SelectAll();
    }
}

 

Default.aspx前台code

 

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>无标题页</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
            <asp:TextBox ID="txtPwd" runat="server"></asp:TextBox>
            <asp:Button ID="subBtn" runat="server" Text="Button" OnClick="subBtn_Click" />
          
            <asp:GridView ID="GridView1" runat="server" Width="427px" AutoGenerateColumns="False" DataKeyNames="Id" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit">
                <Columns>
                    <asp:TemplateField HeaderText="编号">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Id") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label1" runat="server" Text='<%# Bind("Id") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="用户名">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label2" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="密码">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("Pwd") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label3" runat="server" Text='<%# Bind("Pwd") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:CommandField ShowDeleteButton="True" />
                    <asp:CommandField ShowEditButton="True" />
                </Columns>
            </asp:GridView>
        </div>
    </form>
</body>
</html>

hibernate.cfg.xml 文件code 这个放在bin目录 或者 Web.Config 中

<?xml version="1.0" encoding="utf-8"?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory >
   <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
   <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
   <property name="connection.connection_string">Server=.;initial catalog=NHB;User Id=sa;Password=sa;</property>
   <property name="show_sql">true</property>
   <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
   <property name="use_outer_join">true</property>
   <property name="adonet.batch_size">10</property>
   <property name="command_timeout">60</property>
   <property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
   <property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
   <mapping assembly="Models" />
</session-factory>
</hibernate-configuration>

 

Users.hbm.xml实体类映射文件code

 

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-lazy="false">
 <class name="Models.Users, Models" table="Users" dynamic-update="true">
  <id name="Id" column="t_id" type="Int32"  length="4" unsaved-value="0">
   <generator class="native" />
  </id>
  <property name="Name" column="t_name" type="String" length="40" />
  <property name="Pwd" column="t_pwd" type="String" length="40" />
 </class>

</hibernate-mapping>

 

 

Models项目下的 Users

 

using System;
using System.Collections;
using System.Collections.Generic;

namespace Models
{
   /// <summary>
   ///功能描述    :   
   ///开发者      :    杜成刚    
   ///建立时间    :    2010-4-12 22:01:58
   ///修订描述    :   
   ///进度描述    :   
   ///版本号      :    1.0
   ///最后修改时间:    2010-4-12 22:01:58
   ///
   ///Function Description :   
   ///Developer                :   
   ///Builded Date:    2010-4-12 22:01:58
   ///Revision Description :   
   ///Progress Description :   
   ///Version Number        :    1.0
   ///Last Modify Date     :    2010-4-12 22:01:58
   /// </summary>
   public class Users
   {
      #region 构造函数
      public Users()
      {}

      public Users(int id,string name,string pwd)
      {
         this.Id=id;
         this.Name=name;
         this.Pwd=pwd;
      }
      #endregion

      #region 成员
      private int id;
      private string name;
      private string pwd;
      #endregion


      #region 属性
      public  int Id
      {
         get {  return id; }
         set {  id = value; }
      }

      public  string Name
      {
         get {  return name; }
         set {  name = value; }
      }

      public  string Pwd
      {
         get {  return pwd; }
         set {  pwd = value; }
      }

      #endregion

   }
}

 

  该例子要导入的dll文件  我用的是NHibernate2.1.2要用到的dll文件下载 


 

 

 

你可能感兴趣的:(Hibernate)