您的位置:首页 > 其它

Nhibernate学习之many-to-many篇

2008-02-21 15:17 316 查看
学习目的:

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

开发环境+必要准备

开发环境: 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
using System;
using System.Collections.Generic;
using System.Text;

namespace NhibernateSample1

2)User.hbm.xml

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="NhibernateSample1.User,NhibernateSample1" table="Users" lazy="false">
<id name="Id" column="Id" unsaved-value="0">
<generator class="native" />
</id>
<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>
<bag name="DepartmentsList" table="Users_Departments" inverse="true" lazy="false" cascade="all">
<key column="Id"/>
<many-to-many class="NhibernateSample1.Departments,NhibernateSample1" column="DepID"></many-to-many>
</bag>
</class>
</hibernate-mapping>
3) Departments.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace NhibernateSample1

4) Departments.hbm.xml

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="NhibernateSample1.Departments,NhibernateSample1" table="Departments" lazy="false">
<id name="DepID" column="DepID" unsaved-value="0">
<generator class="native" />
</id>
<property name="Name" column="Name" type="string" length="64" not-null="true" unique="true"></property>
<bag name="UsersList" table="Users_Departments" lazy="true" >
<key column="DepID"/>
<many-to-many class="NhibernateSample1.User,NhibernateSample1" column="Id"></many-to-many>
</bag>
</class>
</hibernate-mapping>
5) 数据操作类
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace NhibernateSample1

6)单元测试类

using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NhibernateSample1;

namespace TestProject1

到现在为止,终于更加体会到nhibernate的强大了。继续努力,fight!
files:/Files/jillzhang/simple3.rar
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: