通过进一步学习Nhibernate基础知识,掌握用Nhiberate实现对级联的支持,通过一个简单的用户角色权限系统来体验nhibernate对级联的强大支持。
2)开发环境和必要准备
开发环境为:windows 2003,Visual studio .Net 2005,Sql server 2005 developer edition
必要准备:学习前三篇nhibernate学习系列Nhibernate学习之起步篇-1 ,Nhibernate学习起步之many-to-one篇 ,Nhibernate学习之many-to-many篇
3)示例
业务需求:实现一个用户角色权限系统,一个用户只有一个角色,一个角色下有多个用户,一个角色下有多个权限,一个权限也对应多个角色
要求: (1).创建一个角色 (2)在该角色上创建两个个用户3)创建两个权限4)指定该角色上的权限列表5)获得一个用户的权限列表
首先看关系数据库关系图:
4)实现步骤:
1.User.cs
 using System;
using System; using System.Collections.Generic;
using System.Collections.Generic; using System.Text;
using System.Text;
 namespace NhibernateSample1
namespace NhibernateSample1

 {
{ public class User
    public class User
 
     {
{ private int _id;
        private int _id; private string _name;
        private string _name; private string _pwd;
        private string _pwd; private Role _role;
        private Role _role;
 /**//// <summary>
        /**//// <summary> /// 编号
        /// 编号 /// </summary>
        /// </summary> public virtual int Id
        public virtual int Id
 
         {
{ get
            get
 
             {
{ return _id;
                return _id; }
            } set
            set
 
             {
{ _id = value;
                _id = value; }
            } }
        }

 /**//// <summary>
        /**//// <summary> /// 名称
        /// 名称 /// </summary>
        /// </summary> public virtual string Name
        public virtual string Name
 
         {
{ get
            get
 
             {
{ return _name;
                return _name; }
            } set
            set
 
             {
{ _name = value;
                _name = value; }
            } }
        }

 /**//// <summary>
        /**//// <summary> /// 密码
        /// 密码 /// </summary>
        /// </summary> public virtual string Pwd
        public virtual string Pwd
 
         {
{ get
            get
 
             {
{ return _pwd;
                return _pwd; }
            } set
            set
 
             {
{ _pwd = value;
                _pwd = value; }
            } }
        } public virtual Role Role
        public virtual Role Role
 
         {
{ get
            get
 
             {
{ return _role;
                return _role; }
            } set
            set
 
             {
{ _role = value;
                _role = value; }
            } }
        } }
    } }
}
 <?xml version="1.0" encoding="utf-8" ?>
<?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"> <class name="NhibernateSample1.User,NhibernateSample1" table="Users" lazy="false">
  <class name="NhibernateSample1.User,NhibernateSample1" table="Users" lazy="false"> <id name="Id" column="Id" unsaved-value="0">
    <id name="Id" column="Id" unsaved-value="0"> <generator class="native" />
      <generator class="native" /> </id>
    </id> <property name="Name" column="Name" type="string" length="64" not-null="true" unique="true"></property>
    <property name="Name" column="Name" type="string" length="64" not-null="true" unique="true"></property> <property name="Pwd"  column="Pwd"  type="string" length="64" not-null="true"></property>
    <property name="Pwd"  column="Pwd"  type="string" length="64" not-null="true"></property> <many-to-one name="Role"  class="NhibernateSample1.Role,NhibernateSample1" column="RoleID"></many-to-one>
    <many-to-one name="Role"  class="NhibernateSample1.Role,NhibernateSample1" column="RoleID"></many-to-one> </class>
   </class> </hibernate-mapping>
</hibernate-mapping> using System;
using System; using System.Collections.Generic;
using System.Collections.Generic; using System.Text;
using System.Text; using System.Collections;
using System.Collections;
 namespace NhibernateSample1
namespace NhibernateSample1

 {
{ public class Role
    public class Role
 
     {
{ int _roleID;
        int _roleID; string _roleName;
        string _roleName; IList _list = new  ArrayList();
        IList _list = new  ArrayList(); IList _permissionList = new ArrayList();
        IList _permissionList = new ArrayList(); public virtual IList PermissionList
        public virtual IList PermissionList
 
         {
{ get
            get
 
             {
{ return _permissionList;
                return _permissionList; }
            } set
            set
 
             {
{ _permissionList = value;
                _permissionList = value; }
            } }
        } public virtual int RoleID
        public virtual int RoleID
 
         {
{ get
            get
 
             {
{ return _roleID;
                return _roleID; }
            } set
            set
 
             {
{ _roleID = value;
                _roleID = value; }
            } }
        } public virtual IList UserList
        public virtual IList UserList
 
         {
{ get
            get
 
             {
{ return _list;
                return _list; }
            } set
            set
 
             {
{ _list = value;
                _list = value; }
            } }
        } public virtual string RoleName
        public virtual string RoleName
 
         {
{ get
            get
 
             {
{ return _roleName;
                return _roleName; }
            } set
            set
 
             {
{ _roleName = value;
                _roleName = value; }
            } }
        } }
    } }
}
 <?xml version="1.0" encoding="utf-8" ?>
<?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"> <class name="NhibernateSample1.Role,NhibernateSample1" table="Roles" lazy="false">
  <class name="NhibernateSample1.Role,NhibernateSample1" table="Roles" lazy="false"> <id name="RoleID" column="RoleID" unsaved-value="0">
    <id name="RoleID" column="RoleID" unsaved-value="0"> <generator class="native" />
      <generator class="native" /> </id>
    </id> <property name="RoleName"  column="RoleName"  type="string" length="64" not-null="true"></property>
    <property name="RoleName"  column="RoleName"  type="string" length="64" not-null="true"></property> <bag name="PermissionList" table="Role_Permissions" inverse="true" lazy="false" cascade="all">
    <bag name="PermissionList" table="Role_Permissions" inverse="true" lazy="false" cascade="all"> <key column="RoleID"/>
      <key column="RoleID"/> <many-to-many class="NhibernateSample1.Permission,NhibernateSample1" column="PermissionID"></many-to-many>
      <many-to-many class="NhibernateSample1.Permission,NhibernateSample1" column="PermissionID"></many-to-many> </bag>
    </bag> <bag name="UserList" table="Users" inverse="true" lazy="false" cascade="all">
    <bag name="UserList" table="Users" inverse="true" lazy="false" cascade="all"> <key column="RoleID"/>
      <key column="RoleID"/> <one-to-many class="NhibernateSample1.User,NhibernateSample1"></one-to-many>
      <one-to-many class="NhibernateSample1.User,NhibernateSample1"></one-to-many> </bag>
    </bag> </class>
  </class> </hibernate-mapping>
</hibernate-mapping> using System;
using System; using System.Collections.Generic;
using System.Collections.Generic; using System.Text;
using System.Text; using System.Collections;
using System.Collections;
 namespace NhibernateSample1
namespace NhibernateSample1

 {
{ public class Permission
    public class Permission
 
     {
{ int _permissionID;
        int _permissionID; string _permissionName;
        string _permissionName; IList _roleList = new ArrayList();
        IList _roleList = new ArrayList(); public virtual int PermissionID
        public virtual int PermissionID
 
         {
{ get
            get
 
             {
{ return _permissionID;
                return _permissionID; }
            } set
            set
 
             {
{ _permissionID = value;
                _permissionID = value; }
            } }
        } public virtual string PermissionName
        public virtual string PermissionName
 
         {
{ get
            get
 
             {
{ return _permissionName;
                return _permissionName; }
            } set
            set
 
             {
{ _permissionName=value;
                _permissionName=value; }
            } }
        } public virtual IList RoleList
        public virtual IList RoleList
 
         {
{ get
            get
 
             {
{ return _roleList;
                return _roleList; }
            } set
            set
 
             {
{ _roleList = value;
                _roleList = value; }
            } }
        } }
    } }
}
 <?xml version="1.0" encoding="utf-8" ?>
<?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"> <class name="NhibernateSample1.Permission,NhibernateSample1" table="Permissions" lazy="false">
  <class name="NhibernateSample1.Permission,NhibernateSample1" table="Permissions" lazy="false"> <id name="PermissionID" column="PermissionID" unsaved-value="0">
    <id name="PermissionID" column="PermissionID" unsaved-value="0"> <generator class="native" />
      <generator class="native" /> </id>
    </id> <property name="PermissionName" column="PermissionName" type="string" length="64" not-null="true" unique="true"></property>
    <property name="PermissionName" column="PermissionName" type="string" length="64" not-null="true" unique="true"></property> <bag name="RoleList" table="Role_Permissions"  lazy="true">
    <bag name="RoleList" table="Role_Permissions"  lazy="true"> <key column="PermissionID"/>
      <key column="PermissionID"/> <many-to-many class="NhibernateSample1.Role,NhibernateSample1" column="RoleID"></many-to-many>
      <many-to-many class="NhibernateSample1.Role,NhibernateSample1" column="RoleID"></many-to-many> </bag>
    </bag> </class>
  </class> </hibernate-mapping>
</hibernate-mapping>
 UserRolePermissionFixure
UserRolePermissionFixure using System;
using System; using System.Collections.Generic;
using System.Collections.Generic; using System.Text;
using System.Text; using System.Collections;
using System.Collections; using NHibernate;
using NHibernate; using NHibernate.Cfg;
using NHibernate.Cfg; using NHibernate.Tool.hbm2ddl;
using NHibernate.Tool.hbm2ddl;
 namespace NhibernateSample1
namespace NhibernateSample1

 {
{ public  class UserRolePermissionFixure
    public  class UserRolePermissionFixure
 
     {
{ private ISessionFactory _sessions;
        private ISessionFactory _sessions;  public void Configure()
        public void Configure()
 
         {
{ Configuration cfg = GetConfiguration();
            Configuration cfg = GetConfiguration();       _sessions = cfg.BuildSessionFactory();
            _sessions = cfg.BuildSessionFactory(); }
        } Configuration GetConfiguration()
        Configuration GetConfiguration()
 
         {
{ string cfgPath = @"E:\my project\nhibernate study\simle 1\NHibernateStudy1\NhibernateSample1\hibernate.cfg.xml";
            string cfgPath = @"E:\my project\nhibernate study\simle 1\NHibernateStudy1\NhibernateSample1\hibernate.cfg.xml"; Configuration cfg = new Configuration().Configure(cfgPath);
            Configuration cfg = new Configuration().Configure(cfgPath); return cfg;
            return cfg; }
        } public void ExportTables()
        public void ExportTables()
 
         {
{ Configuration cfg = GetConfiguration();
            Configuration cfg = GetConfiguration();            new SchemaExport(cfg).Create(true, true);
            new SchemaExport(cfg).Create(true, true); }
        } public Role CreateRole(string roleName)
        public Role CreateRole(string roleName)
 
         {
{ Role r = new Role();
            Role r = new Role(); r.RoleName = roleName;
            r.RoleName = roleName; ISession session = _sessions.OpenSession();
            ISession session = _sessions.OpenSession();             ITransaction tx = null;
            ITransaction tx = null; try
            try
 
             {
{ tx = session.BeginTransaction();
                tx = session.BeginTransaction(); session.Save(r);
                session.Save(r); tx.Commit();
                tx.Commit(); }
            } catch(Exception e)
            catch(Exception e)
 
             {
{ if (tx != null) tx.Rollback();
                if (tx != null) tx.Rollback(); throw e;
                throw e; }
            } finally
            finally
 
             {
{ session.Close();
                session.Close(); }
            } return r;
            return r;
 }
        }
 public User CreateUser(String name,string pwd,Role r)
        public User CreateUser(String name,string pwd,Role r)
 
         {
{ User u = new User();
            User u = new User(); u.Name = name;
            u.Name = name; u.Pwd = pwd;
            u.Pwd = pwd; u.Role = r;
            u.Role = r; //r.UserList.Add(u);
            //r.UserList.Add(u); ISession session = _sessions.OpenSession();
            ISession session = _sessions.OpenSession();
 ITransaction tx = null;
            ITransaction tx = null;
 try
            try
 
             {
{ tx = session.BeginTransaction();
                tx = session.BeginTransaction(); session.Save(u);
                session.Save(u); tx.Commit();
                tx.Commit(); }
            } catch (HibernateException e)
            catch (HibernateException e)
 
             {
{ if (tx != null) tx.Rollback();
                if (tx != null) tx.Rollback(); throw e;
                throw e; }
            } finally
            finally
 
             {
{ session.Close();
                session.Close(); }
            }
 return u;
            return u; }
        } public Permission CreatePermission(Role r,string name)
        public Permission CreatePermission(Role r,string name)
 
         {
{ Permission p = new Permission();
            Permission p = new Permission(); p.PermissionName = name;
            p.PermissionName = name; r.PermissionList.Add(p);
            r.PermissionList.Add(p); p.RoleList.Add(r);
            p.RoleList.Add(r); ISession session = _sessions.OpenSession();
            ISession session = _sessions.OpenSession(); ITransaction tx = null;
            ITransaction tx = null;
 try
            try
 
             {
{ tx = session.BeginTransaction();
                tx = session.BeginTransaction(); session.Save(p);
                session.Save(p); tx.Commit();
                tx.Commit(); }
            } catch (HibernateException e)
            catch (HibernateException e)
 
             {
{ if (tx != null) tx.Rollback();
                if (tx != null) tx.Rollback(); throw e;
                throw e; }
            } finally
            finally
 
             {
{ session.Close();
                session.Close(); }
            } return p;
            return p; }
        } public void DeleteRole(int rid)
        public void DeleteRole(int rid)
 
         {
{ ISession session = _sessions.OpenSession();
            ISession session = _sessions.OpenSession(); ITransaction tx = null;
            ITransaction tx = null; try
            try
 
             {
{ tx = session.BeginTransaction();
                tx = session.BeginTransaction(); Role item = session.Load(typeof(Role), rid) as Role;
                Role item = session.Load(typeof(Role), rid) as Role; session.Delete(item);
                session.Delete(item); tx.Commit();
                tx.Commit(); }
            } catch (HibernateException e)
            catch (HibernateException e)
 
             {
{ if (tx != null) tx.Rollback();
                if (tx != null) tx.Rollback(); throw e;
                throw e; }
            } finally
            finally
 
             {
{ session.Close();
                session.Close(); }
            } }
        }
 }
    } }
}

 UnitTest1.cs
UnitTest1.cs using System;
using System; using System.Text;
using System.Text; using System.Collections.Generic;
using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.TestTools.UnitTesting; using NhibernateSample1;
using NhibernateSample1;
 namespace TestProject1
namespace TestProject1

 {
{
 /**//// <summary>
    /**//// <summary> /// UnitTest1 的摘要说明
    /// UnitTest1 的摘要说明 /// </summary>
    /// </summary> [TestClass]
    [TestClass] public class UnitTest1
    public class UnitTest1
 
     {
{ public UnitTest1()
        public UnitTest1()
 
         {
{ //
            // // TODO: 在此处添加构造函数逻辑
            // TODO: 在此处添加构造函数逻辑 //
            // }
        } NhibernateSample1.UserRolePermissionFixure usf = new UserRolePermissionFixure();
        NhibernateSample1.UserRolePermissionFixure usf = new UserRolePermissionFixure();
 其他测试属性#region 其他测试属性
        其他测试属性#region 其他测试属性 //
        // // 您可以在编写测试时使用下列其他属性:
        // 您可以在编写测试时使用下列其他属性: //
        // // 在运行类中的第一个测试之前使用 ClassInitialize 运行代码
        // 在运行类中的第一个测试之前使用 ClassInitialize 运行代码 // [ClassInitialize()]
        // [ClassInitialize()] // public static void MyClassInitialize(TestContext testContext) { }
        // public static void MyClassInitialize(TestContext testContext) { } //
        // // 在类中的所有测试都已运行之后使用 ClassCleanup 运行代码
        // 在类中的所有测试都已运行之后使用 ClassCleanup 运行代码 // [ClassCleanup()]
        // [ClassCleanup()] // public static void MyClassCleanup() { }
        // public static void MyClassCleanup() { } //
        // // 在运行每个测试之前使用 TestInitialize 运行代码
        // 在运行每个测试之前使用 TestInitialize 运行代码  // [TestInitialize()]
        // [TestInitialize()] // public void MyTestInitialize() { }
        // public void MyTestInitialize() { } //
        // // 在运行每个测试之后使用 TestCleanup 运行代码
        // 在运行每个测试之后使用 TestCleanup 运行代码 // [TestCleanup()]
        // [TestCleanup()] // public void MyTestCleanup() { }
        // public void MyTestCleanup() { } //
        // #endregion
        #endregion
 [TestMethod]
        [TestMethod] public void Test1()
        public void Test1()
 
         {
{ usf.Configure();
            usf.Configure(); usf.ExportTables();
            usf.ExportTables(); Role r = usf.CreateRole("test");
            Role r = usf.CreateRole("test"); Assert.IsTrue(r.RoleID > 0);
            Assert.IsTrue(r.RoleID > 0); User u = usf.CreateUser(Guid.NewGuid().ToString(), "ds", r);
            User u = usf.CreateUser(Guid.NewGuid().ToString(), "ds", r);             Assert.IsTrue(u.Id > 0);
            Assert.IsTrue(u.Id > 0); Permission p = usf.CreatePermission(r, "查询");
            Permission p = usf.CreatePermission(r, "查询"); Assert.IsTrue(p.PermissionID > 0);
            Assert.IsTrue(p.PermissionID > 0);          }
        }
 }
    } }
}