nhibernate 的一个小例子

一、开发环境

sql2008,vs2010

1.数据库设计:


2.vs项目中

(1)文档设计图:

(2) 编写持久化类(model)Organization.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NHibernate.Domain
{
    public class Organization
    {
        public int _organizationid;
        public string _organizationname;
        public int _parentid;

        public virtual int OrganizationID
        {
            set { _organizationid = value; }
            get { return _organizationid; }
        }

        public virtual string OrganizationName
        {
            set { _organizationname = value; }
            get { return _organizationname; }
        }

        public virtual int ParentID
        {
            set { _parentid = value; }
            get { return _parentid; }
        }
    }
}
注:别忘了virtual

(2)编写持久化类对于的映射 Organization.hbm.xml

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NHibernate.Domain" namespace="NHibernate.Domain">
  <class name="NHibernate.Domain.Organization,NHibernate.Domain" table="OrganizationTb" lazy="false">
    <id name="OrganizationID" column="OrganizationID" type="Int32">
      <generator class="identity" /> //自增主键用identity, 普通id用<generator class="native" />
    </id>
    <property name="OrganizationName" column="OrganizationName" type="String" length="50" />
    <property name="ParentID" column="ParentID" type="Int32" />
  </class>
</hibernate-mapping>

注:NHibernate.Domain.Organization,NHibernate.Domain 写错的话,会报:VS报错:未能从程序集“Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null”中加载类型“Model.DBModel.Member””

(3)配置NHIbernate   <hibernate.cfg.xml>

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
  <session-factory>
    <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
    <property name="connection.connection_string">Data Source=127.0.0.1;Initial Catalog=organization;Integrated Security=True</property>
    <property name="adonet.batch_size">10</property>
    <property name="show_sql">true</property>
    <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
    <property name="command_timeout">10</property>
    <property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
    <property name="proxyfactory.factory_class">NHibernate.Bytecode.DefaultProxyFactoryFactory, NHibernate</property>
    <mapping assembly="NHibernate.Domain"/>
  </session-factory>
</hibernate-configuration>

注:红字部分是需要修改的

(4)编写工厂类,辅助类 NHibernateHelper.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Cfg;
namespace NHibernate.Domain

{
    public class NHibernateHelper
    {
        public ISessionFactory _sessionFactory
        {
            get;
            set;
        }
        public NHibernateHelper()
        {
            _sessionFactory = GetSessionFactory();
        }

        public ISessionFactory GetSessionFactory()
        {
            return (new Configuration()).Configure().BuildSessionFactory();
        }
        public ISession GetSession()
        {
            return _sessionFactory.OpenSession();
        }

    }
}
(4) 编写操作,集增删改查方法的编写,《ItemList.cs》
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Engine;
namespace NHibernate.Domain
{
    public class ItemList
    {
        public ISession session;
        public ItemList(ISession iSession)
        {
            session = iSession;
        }
        public IList<Organization> GetAllOrganization()
        {
            return session.CreateQuery("from Organization").List<Organization>();
        }
        public IList<Organization> GetOrganizationChild(string parentID)
        {
            return session.CreateQuery("from Organization o where o.ParentID=:parentid").SetString("parentid", parentID).List<Organization>();
        }
        public void UpdateItem(Organization item)
        {
            session.Update(item);
            session.Flush();
        }
        public void DeleteOrganization(Organization item)
        {
            session.Delete(item);
            session.Flush();
        }
        public void InsertOrganization(Organization item)
        {
            session.Save(item);
            session.Flush();
        }
        public IList<string> teststr()
        {
            return session.CreateQuery("select o.OrganizationName from Organization o").List<string>();
        }
    }
}

(5)nhibernate 测试

a.页面的设计

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Organization.aspx.cs" Inherits="Organization.Organization" %>

<!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>
    <style type="text/css">
        body{ text-align:center;}
        h1{ text-align:center; font-size:32px; font-weight:700;}
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>组织结构的维护</h1>
        <asp:GridView runat="server" ID="gridViewO" AutoGenerateColumns="False">
            <Columns>
                <asp:BoundField DataField="OrganizationID" HeaderText="ID" />
                <asp:BoundField DataField="OrganizationName" HeaderText="组织名" />
                <asp:BoundField DataField="ParentID" HeaderText="父组织" />
            </Columns>
        </asp:GridView>
        <br/>
        <asp:TreeView runat="server" ID="tv">
        
        </asp:TreeView>
        <asp:Label runat="server" ID="testLbl"></asp:Label>
       
    </div>
    </form>
</body>
</html>

b.后台调用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Engine;
using NHibernate.Domain;
namespace Organization
{
    public partial class Organization : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
            NHibernateHelper nhHelper = new NHibernateHelper();

            ISessionFactory factory = nhHelper.GetSessionFactory();
            ISession session = factory.OpenSession();
            ItemList itls = new ItemList(session);           

            ITransaction tx = null;
            try
            {
                tx = session.BeginTransaction();
                IList<NHibernate.Domain.Organization> orgs = itls.GetAllOrganization();
                this.gridViewO.DataSource = orgs;
                this.gridViewO.DataBind();
                this.tv.Nodes.Clear();
                TreeNode node = new TreeNode();
                node.Text = "组织结构";
                node.Value = "0";
                AddChild(node);  
                this.tv.Nodes.Add(node);
                 
                tx.Commit();
            }
            catch (Exception)
            {
                tx.Rollback();
                
            }
            finally
            {
                session.Close();
            }  
        }
        public void AddChild(TreeNode nodeParent)
        {
            NHibernateHelper nhHelper = new NHibernateHelper();
            ISessionFactory factory = nhHelper.GetSessionFactory();
            ISession session = factory.OpenSession();
            ItemList itls = new ItemList(session);
            ITransaction tx = session.BeginTransaction();
            try
            {
                IList<NHibernate.Domain.Organization> orgs = itls.GetOrganizationChild(nodeParent.Value);
              
                foreach (var item in orgs)
                {
                    TreeNode childNode = new TreeNode();
                    childNode.Text = item.OrganizationName;
                    childNode.Value = item.OrganizationID.ToString();
                    nodeParent.ChildNodes.Add(childNode);

                    //判断是否有子节点
                    IList<NHibernate.Domain.Organization> orgsChild = itls.GetOrganizationChild(item.OrganizationID.ToString());
                    if (orgsChild.Count!=0)
                    {
                        AddChild(childNode);
                    }
                }             
                tx.Commit();
            }
            catch (Exception)
            {
                tx.Rollback();
                throw;
            }
            finally
            {
                session.Close();
            }
        }
    }
}

(6)运行效果


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值