Nhibernate学习之many-to-many篇

系统 1750 0
  1. 学习目的:

通过进一步学习Nhibernate基础知识,掌握用Nhiberate实现多对多的业务逻辑

  1. 开发环境+必要准备

开发环境: windows 2003,Visual studio .Net 2005,Sql server 2005 developer edition

前期准备: 学习上两篇 单表操作 many-to-one篇

3.对上篇文章的部分解释

1)bag节点:用于定义System.Collection.IList类型的集合元素。

属性

用法

举例

name

映射的属性(必须)

name=”SalaryList”

table

映射的数据表(可选) table=”Salary”
lazy 延迟加载(可选) Lazy=true|false
cascade 指示级联操作方式(可选) Cascade=all
inverse 关联由谁负责维护 Inverse=”true”

当lazy=”true”,父类初始化的时候不会自动加载子类集合

Cascade为级联操作方式,包括:

属性 用法说明
none 默认值,不进行级联操作
save-update save和update级联
delete 删除级联
delete-orphan 删除不相关的父对象的子对象
all save/update/delete级联
all-delete-orphan all+delete-arphan
当inverse=”true”的时候代表由子类维护级联关系。这时候如果只往父类中添加子类,但不设定子类的父类,是不能保存子类的

4.多对多业务模型

还是用户系统,1个用户职员隶属于多个部门,同时1个部门有多个不同的职员
用户和部门之间的数据关系图为:
Nhibernate学习之many-to-many篇
5. 实现步骤:
1)User.cs

User.cs
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>--> using System;
using System.Collections.Generic;
using System.Text;

namespace NhibernateSample1
{
public class User
{
private int _id;
private string _name;
private string _pwd;
private System.Collections.IList_departmentsList;
/**/ /// <summary>
/// 编号
/// </summary>

public virtual int Id
{
get
{
return _id;
}

set
{
_id
= value;
}

}


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

public virtual string Name
{
get
{
return _name;
}

set
{
_name
= value;
}

}


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

public virtual string Pwd
{
get
{
return _pwd;
}

set
{
_pwd
= value;
}

}

/**/ /// <summary>
/// 工资列表
/// </summary>

public System.Collections.IListDepartmentsList
{
get
{
return _departmentsList;
}

set
{
_departmentsList
= value;
}

}

}

}

2)User.hbm.xml

User.hbm.xml
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>--> <? xmlversion = " 1.0 " encoding = " utf-8 " ?>
< hibernate - mappingxmlns = " urn:nhibernate-mapping-2.2 " >
< class name = " NhibernateSample1.User,NhibernateSample1 " table = " Users " lazy = " false " >
< idname = " Id " column = " Id " unsaved - value = " 0 " >
< generator class = " 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 >
< bagname = " DepartmentsList " table = " Users_Departments " inverse = " true " lazy = " false " cascade = " all " >
< keycolumn = " Id " />
< many - to - many class = " NhibernateSample1.Departments,NhibernateSample1 " column = " DepID " ></ many - to - many >
</ bag >
</ class >
</ hibernate - mapping >
3) Departments.cs
Departments
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>--> using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace NhibernateSample1
{
public class Departments
{
int _depID;
string _name;
IList_usersList
= new ArrayList();
public virtual int DepID
{
get
{
return _depID;
}

set
{
_depID
= value;
}

}

public virtual string Name
{
get
{
return _name;
}

set
{
_name
= value;
}

}

public virtual IListUsersList
{
get
{
return _usersList;
}

set
{
_usersList
= value;
}

}

}

}

4) Departments.hbm.xml
Departments.hbm.xml
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>--> <? xmlversion = " 1.0 " encoding = " utf-8 " ?>
< hibernate - mappingxmlns = " urn:nhibernate-mapping-2.2 " >
< class name = " NhibernateSample1.Departments,NhibernateSample1 " table = " Departments " lazy = " false " >
< idname = " DepID " column = " DepID " unsaved - value = " 0 " >
< generator class = " native " />
</ id >
< propertyname = " Name " column = " Name " type = " string " length = " 64 " not - null = " true " unique = " true " ></ property >
< bagname = " UsersList " table = " Users_Departments " lazy = " true " >
< keycolumn = " DepID " />
< many - to - many class = " NhibernateSample1.User,NhibernateSample1 " column = " Id " ></ many - to - many >
</ bag >
</ class >
</ hibernate - mapping >
5) 数据操作类
UserDepartmentFixure.cs
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>--> using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace NhibernateSample1
{
public class UserDepartmentFixure
{
private ISessionFactory_sessions;
public void Configure()
{
Configurationcfg
= GetConfiguration();
_sessions
= cfg.BuildSessionFactory();
}

ConfigurationGetConfiguration()
{
string cfgPath = @" E:/myproject/nhibernatestudy/simle1/NHibernateStudy1/NhibernateSample1/hibernate.cfg.xml " ;
Configurationcfg
= new Configuration().Configure(cfgPath);
return cfg;
}

public void ExportTables()
{
Configurationcfg
= GetConfiguration();
new SchemaExport(cfg).Create( true , true );
}

public UserCreateUser(Stringname, string pwd)
{
Useru
= new User();
u.Name
= name;
u.Pwd
= pwd;
u.DepartmentsList
= new ArrayList();

ISessionsession
= _sessions.OpenSession();

ITransactiontx
= null ;

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

catch (HibernateExceptione)
{
if (tx != null )tx.Rollback();
throw e;
}

finally
{
session.Close();
}


return u;
}

public DepartmentsCreateDepartments(Useru, string name)
{
Departmentsitem
= new Departments();
item.Name
= name;
u.DepartmentsList.Add(item);
item.UsersList.Add(u);
ISessionsession
= _sessions.OpenSession();
ITransactiontx
= null ;

try
{
tx
= session.BeginTransaction();
session.Save(item);
tx.Commit();
}

catch (HibernateExceptione)
{
if (tx != null )tx.Rollback();
throw e;
}

finally
{
session.Close();
}

return item;
}

public DepartmentsGetDepartments( int depID)
{
ISessionsession
= _sessions.OpenSession();
ITransactiontx
= null ;
try
{
tx
= session.BeginTransaction();
Departmentsitem
= (Departments)session.Load( typeof (Departments),
depID);
tx.Commit();
return item;
}

catch (HibernateExceptione)
{
if (tx != null )tx.Rollback();
return null ;
}

finally
{
session.Close();
}

return null ;
}

public UserGetUser( int uid)
{
ISessionsession
= _sessions.OpenSession();
ITransactiontx
= null ;
try
{
tx
= session.BeginTransaction();
Useritem
= (User)session.Load( typeof (User),
uid);
tx.Commit();
return item;
}

catch (HibernateExceptione)
{
if (tx != null )tx.Rollback();
return null ;
}

finally
{
session.Close();
}

return null ;
}


public void Delete( int uid)
{
ISessionsession
= _sessions.OpenSession();
ITransactiontx
= null ;
try
{
tx
= session.BeginTransaction();
Departmentsitem
= session.Load( typeof (Departments),uid) as Departments;
session.Delete(item);
tx.Commit();
}

catch (HibernateExceptione)
{
if (tx != null )tx.Rollback();
throw e;
}

finally
{
session.Close();
}

}


}

}

6)单元测试类
UnitTest1.cs
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>--> using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NhibernateSample1;

namespace TestProject1
{
/**/ /// <summary>
/// UnitTest1的摘要说明
/// </summary>

[TestClass]
public class UnitTest1
{
public UnitTest1()
{
//
// TODO:在此处添加构造函数逻辑
//
}

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


[TestMethod]
public void Test1()
{
usf.Configure();
usf.ExportTables();
Useru
= usf.CreateUser(Guid.NewGuid().ToString(), " ds " );
Assert.IsTrue(u.Id
> 0 );
Departmentss
= usf.CreateDepartments(u, " 政治部 " );
Assert.IsTrue(s.DepID
> 0 );
Departmentss1
= usf.CreateDepartments(u, " 事业部 " );
Assert.IsTrue(s1.DepID
> 0 );
usf.Delete(s1.DepID);
s1
= usf.GetDepartments(s1.DepID);
Assert.IsNull(s1);
Useru1
= usf.GetUser( 1 );
Assert.IsTrue(u1.DepartmentsList.Count
> 0 );
}


}

}

到现在为止,终于更加体会到nhibernate的强大了。继续努力,fight!
files: /Files/jillzhang/simple3.rar
上几篇文章: Nhibernate学习之起步篇-1
Nhibernate分析之华山论剑篇
Nhibernate学习起步之many-to-one篇

Nhibernate学习之many-to-many篇


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论