1) 学习目标
通过进一步学习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
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;

namespaceNhibernateSample1


{
publicclassUser


{
privateint_id;
privatestring_name;
privatestring_pwd;
privateRole_role;

/**////<summary>
///编号
///</summary>
publicvirtualintId


{
get


{
return_id;
}
set


{
_id=value;
}
}


/**////<summary>
///名称
///</summary>
publicvirtualstringName


{
get


{
return_name;
}
set


{
_name=value;
}
}


/**////<summary>
///密码
///</summary>
publicvirtualstringPwd


{
get


{
return_pwd;
}
set


{
_pwd=value;
}
}
publicvirtualRoleRole


{
get


{
return_role;
}
set


{
_role=value;
}
}
}
}
User.hbm.xml
<?xmlversion="1.0"encoding="utf-8"?>
<hibernate-mappingxmlns="urn:nhibernate-mapping-2.2">
<classname="NhibernateSample1.User,NhibernateSample1"table="Users"lazy="false">
<idname="Id"column="Id"unsaved-value="0">
<generatorclass="native"/>
</id>
<propertyname="Name"column="Name"type="string"length="64"not-null="true"unique="true"></property>
<propertyname="Pwd"column="Pwd"type="string"length="64"not-null="true"></property>
<many-to-onename="Role"class="NhibernateSample1.Role,NhibernateSample1"column="RoleID"></many-to-one>
</class>
</hibernate-mapping>
2.Role.cs
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.Collections;

namespaceNhibernateSample1


{
publicclassRole


{
int_roleID;
string_roleName;
IList_list=newArrayList();
IList_permissionList=newArrayList();
publicvirtualIListPermissionList


{
get


{
return_permissionList;
}
set


{
_permissionList=value;
}
}
publicvirtualintRoleID


{
get


{
return_roleID;
}
set


{
_roleID=value;
}
}
publicvirtualIListUserList


{
get


{
return_list;
}
set


{
_list=value;
}
}
publicvirtualstringRoleName


{
get


{
return_roleName;
}
set


{
_roleName=value;
}
}
}
}
Role.hbm.xml
<?xmlversion="1.0"encoding="utf-8"?>
<hibernate-mappingxmlns="urn:nhibernate-mapping-2.2">
<classname="NhibernateSample1.Role,NhibernateSample1"table="Roles"lazy="false">
<idname="RoleID"column="RoleID"unsaved-value="0">
<generatorclass="native"/>
</id>
<propertyname="RoleName"column="RoleName"type="string"length="64"not-null="true"></property>
<bagname="PermissionList"table="Role_Permissions"inverse="true"lazy="false"cascade="all">
<keycolumn="RoleID"/>
<many-to-manyclass="NhibernateSample1.Permission,NhibernateSample1"column="PermissionID"></many-to-many>
</bag>
<bagname="UserList"table="Users"inverse="true"lazy="false"cascade="all">
<keycolumn="RoleID"/>
<one-to-manyclass="NhibernateSample1.User,NhibernateSample1"></one-to-many>
</bag>
</class>
</hibernate-mapping>
3.Permission.cs
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.Collections;

namespaceNhibernateSample1


{
publicclassPermission


{
int_permissionID;
string_permissionName;
IList_roleList=newArrayList();
publicvirtualintPermissionID


{
get


{
return_permissionID;
}
set


{
_permissionID=value;
}
}
publicvirtualstringPermissionName


{
get


{
return_permissionName;
}
set


{
_permissionName=value;
}
}
publicvirtualIListRoleList


{
get


{
return_roleList;
}
set


{
_roleList=value;
}
}
}
}
Permission.hbm.xml
<?xmlversion="1.0"encoding="utf-8"?>
<hibernate-mappingxmlns="urn:nhibernate-mapping-2.2">
<classname="NhibernateSample1.Permission,NhibernateSample1"table="Permissions"lazy="false">
<idname="PermissionID"column="PermissionID"unsaved-value="0">
<generatorclass="native"/>
</id>
<propertyname="PermissionName"column="PermissionName"type="string"length="64"not-null="true"unique="true"></property>
<bagname="RoleList"table="Role_Permissions"lazy="true">
<keycolumn="PermissionID"/>
<many-to-manyclass="NhibernateSample1.Role,NhibernateSample1"column="RoleID"></many-to-many>
</bag>
</class>
</hibernate-mapping>
4。数据操作类

UserRolePermissionFixure
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>-->
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.Collections;
usingNHibernate;
usingNHibernate.Cfg;
usingNHibernate.Tool.hbm2ddl;

namespaceNhibernateSample1


{
publicclassUserRolePermissionFixure


{
privateISessionFactory_sessions;
publicvoidConfigure()


{
Configurationcfg=GetConfiguration();
_sessions=cfg.BuildSessionFactory();
}
ConfigurationGetConfiguration()


{
stringcfgPath=@"E:/myproject/nhibernatestudy/simle1/NHibernateStudy1/NhibernateSample1/hibernate.cfg.xml";
Configurationcfg=newConfiguration().Configure(cfgPath);
returncfg;
}
publicvoidExportTables()


{
Configurationcfg=GetConfiguration();
newSchemaExport(cfg).Create(true,true);
}
publicRoleCreateRole(stringroleName)


{
Roler=newRole();
r.RoleName=roleName;
ISessionsession=_sessions.OpenSession();
ITransactiontx=null;
try


{
tx=session.BeginTransaction();
session.Save(r);
tx.Commit();
}
catch(Exceptione)


{
if(tx!=null)tx.Rollback();
throwe;
}
finally


{
session.Close();
}
returnr;

}

publicUserCreateUser(Stringname,stringpwd,Roler)


{
Useru=newUser();
u.Name=name;
u.Pwd=pwd;
u.Role=r;
//r.UserList.Add(u);
ISessionsession=_sessions.OpenSession();

ITransactiontx=null;

try


{
tx=session.BeginTransaction();
session.Save(u);
tx.Commit();
}
catch(HibernateExceptione)


{
if(tx!=null)tx.Rollback();
throwe;
}
finally


{
session.Close();
}

returnu;
}
publicPermissionCreatePermission(Roler,stringname)


{
Permissionp=newPermission();
p.PermissionName=name;
r.PermissionList.Add(p);
p.RoleList.Add(r);
ISessionsession=_sessions.OpenSession();
ITransactiontx=null;

try


{
tx=session.BeginTransaction();
session.Save(p);
tx.Commit();
}
catch(HibernateExceptione)


{
if(tx!=null)tx.Rollback();
throwe;
}
finally


{
session.Close();
}
returnp;
}
publicvoidDeleteRole(intrid)


{
ISessionsession=_sessions.OpenSession();
ITransactiontx=null;
try


{
tx=session.BeginTransaction();
Roleitem=session.Load(typeof(Role),rid)asRole;
session.Delete(item);
tx.Commit();
}
catch(HibernateExceptione)


{
if(tx!=null)tx.Rollback();
throwe;
}
finally


{
session.Close();
}
}

}
}
5。单元测试类

UnitTest1.cs
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>-->
usingSystem;
usingSystem.Text;
usingSystem.Collections.Generic;
usingMicrosoft.VisualStudio.TestTools.UnitTesting;
usingNhibernateSample1;

namespaceTestProject1


{

/**////<summary>
///UnitTest1的摘要说明
///</summary>
[TestClass]
publicclassUnitTest1


{
publicUnitTest1()


{
//
//TODO:在此处添加构造函数逻辑
//
}
NhibernateSample1.UserRolePermissionFixureusf=newUserRolePermissionFixure();

其他测试属性#region其他测试属性
//
//您可以在编写测试时使用下列其他属性:
//
//在运行类中的第一个测试之前使用ClassInitialize运行代码
//[ClassInitialize()]
//publicstaticvoidMyClassInitialize(TestContexttestContext){}
//
//在类中的所有测试都已运行之后使用ClassCleanup运行代码
//[ClassCleanup()]
//publicstaticvoidMyClassCleanup(){}
//
//在运行每个测试之前使用TestInitialize运行代码
//[TestInitialize()]
//publicvoidMyTestInitialize(){}
//
//在运行每个测试之后使用TestCleanup运行代码
//[TestCleanup()]
//publicvoidMyTestCleanup(){}
//
#endregion

[TestMethod]
publicvoidTest1()


{
usf.Configure();
usf.ExportTables();
Roler=usf.CreateRole("test");
Assert.IsTrue(r.RoleID>0);
Useru=usf.CreateUser(Guid.NewGuid().ToString(),"ds",r);
Assert.IsTrue(u.Id>0);
Permissionp=usf.CreatePermission(r,"查询");
Assert.IsTrue(p.PermissionID>0);
}

}
}
通过本篇的学习,将充分理解到nhibernate对级联支持的强大。另外除了支持三级联之外,他还支持异类关联(Heterogeneous Associations) .给开发带来了更多的灵活性和实用性。而且考虑到性能的问题,还添加了lazy这样的延迟加载的功能,加载父亲不必要一定要加载他的儿子集合。通过集合类映射,nhinernate轻松实现级联,这相比较代码生成来说,无疑是一个优点。
相关文章:
-
2021-10-14
-
2021-12-26
-
2021-10-01
猜你喜欢
-
2021-09-25
-
2021-04-30
-
2022-01-31
相关资源
-
下载
2023-01-18
-
下载
2023-02-09
-
下载
2021-06-06