Nhibernate学习之many-to-many篇

  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-updatesave和update级联
delete删除级联
delete-orphan删除不相关的父对象的子对象
allsave/update/delete级联
all-delete-orphanall+delete-arphan
   当inverse=”true”的时候代表由子类维护级联关系。这时候如果只往父类中添加子类,但不设定子类的父类,是不能保存子类的

 4.多对多业务模型

    还是用户系统,1个用户职员隶属于多个部门,同时1个部门有多个不同的职员 
    用户和部门之间的数据关系图为:

5.  实现步骤:
  1)User.cs

ContractedBlock.gif ExpandedBlockStart.gif User.cs
None.gifusing System;
None.gif
using System.Collections.Generic;
None.gif
using System.Text;
None.gif
None.gif
namespace NhibernateSample1
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
public class User
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
private int _id;
InBlock.gif        
private string _name;
InBlock.gif        
private string _pwd;
InBlock.gif        
private System.Collections.IList _departmentsList;
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 编号
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public virtual int Id
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
get
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return _id;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
set
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                _id 
= value;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 名称
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public virtual string Name
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
get
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return _name;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
set
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                _name 
= value;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 密码
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public virtual string Pwd
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
get
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return _pwd;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
set
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                _pwd 
= value;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 工资列表
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public System.Collections.IList DepartmentsList
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
get
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return _departmentsList;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
set
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                _departmentsList 
= value;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif

  2)User.hbm.xml 

ContractedBlock.gif ExpandedBlockStart.gif User.hbm.xml
None.gif<?xml version="1.0" encoding="utf-8" ?>
None.gif
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
None.gif  
<class name="NhibernateSample1.User,NhibernateSample1" table="Users" lazy="false">
None.gif    
<id name="Id" column="Id" unsaved-value="0">
None.gif      
<generator class="native" />
None.gif    
</id>
None.gif    
<property name="Name" column="Name" type="string" length="64" not-null="true" unique="true"></property>
None.gif    
<property name="Pwd"  column="Pwd"  type="string" length="64" not-null="true"></property>
None.gif    
<bag name="DepartmentsList" table="Users_Departments" inverse="true" lazy="false" cascade="all">
None.gif      
<key column="Id"/>
None.gif      
<many-to-many class="NhibernateSample1.Departments,NhibernateSample1" column="DepID"></many-to-many>
None.gif    
</bag>
None.gif  
</class>
None.gif
</hibernate-mapping>
  3) Departments.cs
ContractedBlock.gif ExpandedBlockStart.gif Departments
None.gifusing System;
None.gif
using System.Collections.Generic;
None.gif
using System.Text;
None.gif
using System.Collections;
None.gif
None.gif
namespace NhibernateSample1
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
public class Departments
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
int _depID;
InBlock.gif        
string _name;
InBlock.gif        IList _usersList
= new ArrayList();
InBlock.gif        
public virtual int DepID
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
get
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return _depID;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
set
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                _depID 
= value;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif        
public virtual string Name
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
get
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return _name;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
set
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                _name 
= value;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif        
public virtual IList UsersList
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
get
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return _usersList;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
set
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                _usersList 
= value;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
4) Departments.hbm.xml
ContractedBlock.gif ExpandedBlockStart.gif Departments.hbm.xml
None.gif<?xml version="1.0" encoding="utf-8" ?>
None.gif
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
None.gif  
<class name="NhibernateSample1.Departments,NhibernateSample1" table="Departments" lazy="false">
None.gif    
<id name="DepID" column="DepID" unsaved-value="0">
None.gif      
<generator class="native" />
None.gif    
</id>
None.gif    
<property name="Name" column="Name" type="string" length="64" not-null="true" unique="true"></property>   
None.gif    
<bag name="UsersList" table="Users_Departments"  lazy="true" >
None.gif      
<key column="DepID"/>
None.gif      
<many-to-many class="NhibernateSample1.User,NhibernateSample1" column="Id"></many-to-many>
None.gif    
</bag>
None.gif  
</class>
None.gif
</hibernate-mapping>
5) 数据操作类 
ContractedBlock.gif ExpandedBlockStart.gif UserDepartmentFixure.cs
None.gifusing System;
None.gif
using System.Collections.Generic;
None.gif
using System.Text;
None.gif
using System.Collections;
None.gif
using NHibernate;
None.gif
using NHibernate.Cfg;
None.gif
using NHibernate.Tool.hbm2ddl;
None.gif
None.gif
namespace NhibernateSample1
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
public  class UserDepartmentFixure
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
private ISessionFactory _sessions; 
InBlock.gif        
public void Configure()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Configuration cfg 
= GetConfiguration();      
InBlock.gif            _sessions 
= cfg.BuildSessionFactory();
ExpandedSubBlockEnd.gif        }

InBlock.gif        Configuration GetConfiguration()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
string cfgPath = @"E:\my project\nhibernate study\simle 1\NHibernateStudy1\NhibernateSample1\hibernate.cfg.xml";
InBlock.gif            Configuration cfg 
= new Configuration().Configure(cfgPath);
InBlock.gif            
return cfg;
ExpandedSubBlockEnd.gif        }

InBlock.gif        
public void ExportTables()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Configuration cfg 
= GetConfiguration();           
InBlock.gif            
new SchemaExport(cfg).Create(truetrue);
ExpandedSubBlockEnd.gif        }

InBlock.gif        
public User CreateUser(String name,string pwd)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            User u 
= new User();
InBlock.gif            u.Name 
= name;
InBlock.gif            u.Pwd 
= pwd;
InBlock.gif            u.DepartmentsList 
= new ArrayList();
InBlock.gif
InBlock.gif            ISession session 
= _sessions.OpenSession();
InBlock.gif
InBlock.gif            ITransaction tx 
= null;
InBlock.gif
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                tx 
= session.BeginTransaction();
InBlock.gif                session.Save(u);
InBlock.gif                tx.Commit();
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch (HibernateException e)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if (tx != null) tx.Rollback();
InBlock.gif                
throw e;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
finally
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                session.Close();
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
return u;
ExpandedSubBlockEnd.gif        }

InBlock.gif        
public Departments CreateDepartments(User u, string name)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Departments item 
= new Departments();
InBlock.gif            item.Name
=name;
InBlock.gif            u.DepartmentsList.Add(item);
InBlock.gif            item.UsersList.Add(u);
InBlock.gif            ISession session 
= _sessions.OpenSession();
InBlock.gif            ITransaction tx 
= null;
InBlock.gif
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                tx 
= session.BeginTransaction();
InBlock.gif                session.Save(item);
InBlock.gif                tx.Commit();
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch (HibernateException e)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if (tx != null) tx.Rollback();
InBlock.gif                
throw e;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
finally
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                session.Close();
ExpandedSubBlockEnd.gif            }

InBlock.gif            
return item;
ExpandedSubBlockEnd.gif        }
       
InBlock.gif        
public Departments GetDepartments(int depID)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            ISession session 
= _sessions.OpenSession();
InBlock.gif            ITransaction tx 
= null;
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                tx 
= session.BeginTransaction();
InBlock.gif                Departments item 
= (Departments)session.Load(typeof(Departments),
InBlock.gif                    depID);               
InBlock.gif                tx.Commit();
InBlock.gif                
return item;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch (HibernateException e)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if (tx != null) tx.Rollback();
InBlock.gif                
return null;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
finally
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                session.Close();
ExpandedSubBlockEnd.gif            }

InBlock.gif            
return null;
ExpandedSubBlockEnd.gif        }

InBlock.gif        
public User GetUser(int uid)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            ISession session 
= _sessions.OpenSession();
InBlock.gif            ITransaction tx 
= null;
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                tx 
= session.BeginTransaction();
InBlock.gif                User item 
= (User)session.Load(typeof(User),
InBlock.gif                    uid);
InBlock.gif                tx.Commit();
InBlock.gif                
return item;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch (HibernateException e)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if (tx != null) tx.Rollback();
InBlock.gif                
return null;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
finally
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                session.Close();
ExpandedSubBlockEnd.gif            }

InBlock.gif            
return null;
ExpandedSubBlockEnd.gif        }
       
InBlock.gif
InBlock.gif        
public void Delete(int uid)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            ISession session 
= _sessions.OpenSession();
InBlock.gif            ITransaction tx 
= null;
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                tx 
= session.BeginTransaction();
InBlock.gif                Departments item 
= session.Load(typeof(Departments), uid) as Departments;
InBlock.gif                session.Delete(item);
InBlock.gif                tx.Commit();
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch (HibernateException e)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if (tx != null) tx.Rollback();
InBlock.gif                
throw e;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
finally
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                session.Close();
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
6)单元测试类
ContractedBlock.gif ExpandedBlockStart.gif UnitTest1.cs
None.gifusing System;
None.gif
using System.Text;
None.gif
using System.Collections.Generic;
None.gif
using Microsoft.VisualStudio.TestTools.UnitTesting;
None.gif
using NhibernateSample1;
None.gif
None.gif
namespace TestProject1
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
InBlock.gif    
/// UnitTest1 的摘要说明
ExpandedSubBlockEnd.gif    
/// </summary>

InBlock.gif    [TestClass]
InBlock.gif    
public class UnitTest1
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
public UnitTest1()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
//
InBlock.gif            
// TODO: 在此处添加构造函数逻辑
InBlock.gif            
//
ExpandedSubBlockEnd.gif
        }

InBlock.gif        NhibernateSample1.UserDepartmentFixure usf 
= new UserDepartmentFixure();
ContractedSubBlock.gifExpandedSubBlockStart.gif        
其他测试属性#region 其他测试属性
InBlock.gif        
//
InBlock.gif        
// 您可以在编写测试时使用下列其他属性:
InBlock.gif        
//
InBlock.gif        
// 在运行类中的第一个测试之前使用 ClassInitialize 运行代码
InBlock.gif        
// [ClassInitialize()]
InBlock.gif        
// public static void MyClassInitialize(TestContext testContext) { }
InBlock.gif        
//
InBlock.gif        
// 在类中的所有测试都已运行之后使用 ClassCleanup 运行代码
InBlock.gif        
// [ClassCleanup()]
InBlock.gif        
// public static void MyClassCleanup() { }
InBlock.gif        
//
InBlock.gif        
// 在运行每个测试之前使用 TestInitialize 运行代码 
InBlock.gif        
// [TestInitialize()]
InBlock.gif        
// public void MyTestInitialize() { }
InBlock.gif        
//
InBlock.gif        
// 在运行每个测试之后使用 TestCleanup 运行代码
InBlock.gif        
// [TestCleanup()]
InBlock.gif        
// public void MyTestCleanup() { }
InBlock.gif        
//
ExpandedSubBlockEnd.gif
        #endregion

InBlock.gif
InBlock.gif        [TestMethod]
InBlock.gif        
public void Test1()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            usf.Configure();
InBlock.gif            usf.ExportTables();
InBlock.gif            User u 
= usf.CreateUser(Guid.NewGuid().ToString(), "ds");
InBlock.gif            Assert.IsTrue(u.Id
>0);
InBlock.gif            Departments s 
= usf.CreateDepartments(u, "政治部");
InBlock.gif            Assert.IsTrue(s.DepID 
> 0);
InBlock.gif            Departments s1 
= usf.CreateDepartments(u, "事业部");
InBlock.gif            Assert.IsTrue(s1.DepID 
> 0);         
InBlock.gif            usf.Delete(s1.DepID);
InBlock.gif            s1 
= usf.GetDepartments(s1.DepID);
InBlock.gif            Assert.IsNull(s1);
InBlock.gif            User u1 
= usf.GetUser(1);
InBlock.gif            Assert.IsTrue(u1.DepartmentsList.Count
>0);
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
到现在为止,终于更加体会到nhibernate的强大了。继续努力,fight!
files: /Files/jillzhang/simple3.rar
上几篇文章:   Nhibernate学习之起步篇-1 
               Nhibernate分析之华山论剑篇 
               Nhibernate学习起步之many-to-one篇
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值