我的NHibernate之路(3)---表間多對多配置篇
本節(jié)要點(diǎn):
1、如何配置表之間多對多的關(guān)系
2、多表之間如何進(jìn)行操作
對于關(guān)系型數(shù)據(jù)庫,表之間也多對多的關(guān)系也很常見的。在我們實(shí)際開發(fā)過程中如何進(jìn)行正確的映射的配置,以及所關(guān)聯(lián)的表之間是如何操作的?這是本文講述的重點(diǎn)。
開發(fā)環(huán)境:VS2008 SP1 使用的NHibernate版本:NHibernate-2.1.2.GA-bin。
將上節(jié)討論的學(xué)生表與班級(jí)表再進(jìn)行深層次的引入:如果構(gòu)建一個(gè)學(xué)生選課的數(shù)據(jù)庫,還需要什么表?表之間的關(guān)系如何對應(yīng)?還是通過LINQ的截圖說說表的字段以及表之間的關(guān)系【不討論LINQ與Nhibernate之間的關(guān)系,免得又有朋友誤解】。圖如下:

通過圖,可以很清楚的看出四張表見的關(guān)系。不過我主要說的是下面三張表。
對于學(xué)生來說,他可以選擇多門課程。對于課程來說,多個(gè)學(xué)生也可以選擇同一門課程。對于學(xué)生實(shí)體類和課程實(shí)體類,他們之間就是一種多對多的關(guān)系。順便給出下面三張表之間的外鍵。students表與SelectCourse:引用列【ID】與被引用列【Students】,外鍵名:FK_SelectCourse_Students。Course表與SelectCourse表:引用列【ID】與被引用列【CourseID】,外鍵名:FK_SelectCourse_Course。被引用類那么他們之間的映射關(guān)系如何?
通過上節(jié)的說明,一對多是在映射文件中通過one-to-many表示的。大家很自然想到多對多就是通過many-to-many來表示。有了一對多配置的基礎(chǔ),我就說說其中重要的。
Stuents表的映射文件:
1 <?xml version="1.0" encoding="utf-8" ?>
2 <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
3 <class name="MultiToMultiModel.Student, MultiToMultiModel" table="Students">
4 <id name="Id" type="Int32" unsaved-value="0">
5 <column name="ID" length="4" sql-type="int" not-null="true" unique="true"
index="PK_Students"/>
6 <generator class="native" />
7 </id>
8 <property name="Name" type="String">
9 <column name="Name" length="50" sql-type="varchar" not-null="false"/>
10 </property>
11 <property name="Phone" type="String">
12 <column name="Phone" length="15" sql-type="varchar" not-null="false"/>
13 </property>
14 <many-to-one name="Class" class="MultiToMultiModel.Class, MultiToMultiModel">
15 <column name="ClassID" length="4" sql-type="int" not-null="false"/>
16 </many-to-one>
17
18 <bag name="Courses" generic="true" table="SelectCourse">
19 <key column="StudentID" foreign-key="FK_SelectCourse_Students" not-null="false"></key>
20 <many-to-many column="CourseID" foreign-key="FK_SelectCourse_Course"
class="MultiToMultiModel.Course,MultiToMultiModel"></many-to-many>
21 </bag>
22 </class>
23 </hibernate-mapping>
24
Students對應(yīng)的實(shí)體類:
代碼
1
2 using System;
3 using System.Collections.Generic;
4 using System.Collections;
5
6
7 namespace MultiToMultiModel
8 {
9 #region Student
10
11 /// <summary>
12 /// Student object for NHibernate mapped table 'Students'.
13 /// </summary>
14 public class Student
15 {
16 #region Member Variables
17
18 protected int _id;
19 protected string _name;
20 protected string _phone;
21 protected Class _class;
22 //protected IList _studentSelectCourses;
23 protected IList<Course> _courses;
24 #endregion
25
26 #region Constructors
27
28 public Student() { }
29
30 public Student( string name, string phone, Class _class )
31 {
32 this._name = name;
33 this._phone = phone;
34 this._class = _class;
35 }
36
37 #endregion
38
39 #region Public Properties
40
41 public virtual int Id
42 {
43 get {return _id;}
44 set {_id = value;}
45 }
46
47 public virtual string Name
48 {
49 get { return _name; }
50 set
51 {
52 if ( value != null && value.Length > 50)
53 throw new ArgumentOutOfRangeException("Invalid value for Name", value, value.ToString());
54 _name = value;
55 }
56 }
57
58 public virtual string Phone
59 {
60 get { return _phone; }
61 set
62 {
63 if ( value != null && value.Length > 15)
64 throw new ArgumentOutOfRangeException("Invalid value for Phone", value, value.ToString());
65 _phone = value;
66 }
67 }
68
69 public virtual Class Class
70 {
71 get { return _class; }
72 set { _class = value; }
73 }
74
75 public virtual IList<Course> Courses
76 {
77 get
78 {
79 if (_courses == null)
80 {
81 _courses = new List<Course>();
82 }
83 return _courses;
84 }
85 set { _courses = value; }
86 }
87 #endregion
88
89 }
90
91 #endregion
92 }
93
Course表對應(yīng)的映射文件:
1 <?xml version="1.0" encoding="utf-8" ?>
2 <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
3 <class name="MultiToMultiModel.Course, MultiToMultiModel" table="Course">
4 <id name="Id" type="Int32" unsaved-value="0">
5 <column name="ID" length="4" sql-type="int" not-null="true" unique="true" index="PK_Course"/>
6 <generator class="native" />
7 </id>
8 <property name="CourseName" type="String">
9 <column name="CourseName" length="50" sql-type="varchar" not-null="false"/>
10 </property>
11 <property name="Teacher" type="String">
12 <column name="Teacher" length="50" sql-type="varchar" not-null="false"/>
13 </property>
14 <property name="Time" type="DateTime">
15 <column name="`Time`" length="8" sql-type="datetime" not-null="false"/>
16 </property>
17 <property name="Address" type="String">
18 <column name="Address" length="50" sql-type="varchar" not-null="false"/>
19 </property>
20
21 <bag name="Students" generic="true" table="SelectCourse" >
22 <key column="CourseID" foreign-key="FK_SelectCourse_Course" not-null="false"></key>
23 <many-to-many column="StudentID" class="MultiToMultiModel.Student,MultiToMultiModel"
foreign-key="FK_SelectCourse_Students"></many-to-many>
24 </bag>
25 </class>
26 </hibernate-mapping>
27
對應(yīng)的實(shí)體類:
1 using System;
2 using System.Collections.Generic;
3 using System.Collections;
4
5
6 namespace MultiToMultiModel
7 {
8 #region Course
9
10 /// <summary>
11 /// Course object for NHibernate mapped table 'Course'.
12 /// </summary>
13 public class Course
14 {
15 #region Member Variables
16
17 protected int _id;
18 protected string _courseName;
19 protected string _teacher;
20 protected DateTime _time;
21 protected string _address;
22 protected IList<Student> _students;
23
24
25 #endregion
26
27 #region Constructors
28
29 public Course() { }
30
31 public Course( string courseName, string teacher, DateTime time, string address )
32 {
33 this._courseName = courseName;
34 this._teacher = teacher;
35 this._time = time;
36 this._address = address;
37 }
38
39 #endregion
40
41 #region Public Properties
42
43 public virtual int Id
44 {
45 get {return _id;}
46 set {_id = value;}
47 }
48
49 public virtual string CourseName
50 {
51 get { return _courseName; }
52 set
53 {
54 if ( value != null && value.Length > 50)
55 throw new ArgumentOutOfRangeException("Invalid value for CourseName", value, value.ToString());
56 _courseName = value;
57 }
58 }
59
60 public virtual string Teacher
61 {
62 get { return _teacher; }
63 set
64 {
65 if ( value != null && value.Length > 50)
66 throw new ArgumentOutOfRangeException("Invalid value for Teacher", value, value.ToString());
67 _teacher = value;
68 }
69 }
70
71 public virtual DateTime Time
72 {
73 get { return _time; }
74 set { _time = value; }
75 }
76
77 public virtual string Address
78 {
79 get { return _address; }
80 set
81 {
82 if ( value != null && value.Length > 50)
83 throw new ArgumentOutOfRangeException("Invalid value for Address", value, value.ToString());
84 _address = value;
85 }
86 }
87
88 public virtual IList<Student> Students
89 {
90 get
91 {
92 if (_students == null)
93 {
94 _students = new List<Student>();
95 }
96 return _students;
97 }
98 set { _students = value; }
99 }
100
101 #endregion
102
103
104 }
105
106 #endregion
107 }
108
對于實(shí)體類,就不用說了。主要說說映射文件中的<bag>節(jié)點(diǎn)的配置。
bag:對象集合。集合中的元素可以重復(fù)。相當(dāng)于.Net中的IList或者IList<T>。當(dāng)然對應(yīng)的name是相應(yīng)實(shí)體類的屬性了。
我個(gè)人最為關(guān)鍵的的是KEY、與many-to-mnay兩個(gè)階段的配置與理解。首先對于兩個(gè)實(shí)體類,我應(yīng)該建立他們各自的映射文件,這是最基本的。我就以Course表來說。它與Students表多對多的關(guān)系是通過SelectCourse表建立的。要給Course實(shí)體類建立與Students的映射關(guān)系,唯一的途徑就是通過SelectCourse表上的外鍵FK_SelectCourse_Course。而外鍵FK_SelectCourse_Course是引用的Course表的主鍵。
所以對key節(jié)點(diǎn):他對應(yīng)的column【對應(yīng)表的列明,這里就不再具體多說】當(dāng)然是CourseID。
對于many-to-many節(jié)點(diǎn),我是這樣理解的。既然是多對多。第一個(gè)many指的當(dāng)然是它自己,即Course,另外一個(gè)顯然是針對Students。那么Students與Course建立對應(yīng)關(guān)系的唯一途徑也只有通過引用在它的主鍵上建立的外鍵FK_SelectCourse_Students。后面對應(yīng)的是實(shí)體類Students對應(yīng)的程序集以及指明Course多對多的實(shí)體類Student。
映射文件小結(jié):
key節(jié)點(diǎn):是對于映射文件對應(yīng)的實(shí)體類所說的。
many-to-many:是對多對多中另外“多”的一方說的
映射文件的介紹與說明就到這。下面說說它們之間該如何做操作。我僅僅以添加為例進(jìn)行說明。
添加的需求說明:我希望為一個(gè)學(xué)生添加他所選的課程,并將此學(xué)生添加到一個(gè)新的班級(jí)中【課程也要求新添加到課程表】。還是直接上代碼較為直接:
代碼
1 //申明對象
2 Class cls = new Class();
3 Student stu = new Student();
4 Course c = new Course();
5
6 SelectCourse _selectCourse = new SelectCourse();
7
8
9 cls.ClassCode = "03510236";
10 cls.ClassStudentses.Add(stu);
11 cls.StudentsAmount = 36;
12
13 stu.Class = cls;
14 stu.Name = "teau";
15 stu.Phone = "0897658";
16 stu.Courses = new List<Course>();
17 stu.Courses.Add(c);
18
19
20 c.Address = "Beijing";
21 c.CourseName = "C++";
22 c.Students = new List<Student>();
23 c.Students.Add(stu);
24 c.Teacher = "Tao";
25 c.Time = DateTime.Now;
26
27 _selectCourse.Course = c;
28 _selectCourse.Student = stu;
29
30
31 ClassBLL cBLl = new ClassBLL();
32 CourseBLL courseBLL = new CourseBLL();
33 try
34 {
35 if (cBLl != null && cls != null)
36 {
37 ClassBLL.AddClass(cls);
38 CourseBLL.AddCourse(c);
39 SelectCourseBLL.AddSelectCourse(_selectCourse);
40 }
41 }
42 catch (Exception ex)
43 {
44 throw ex;
45 }
上述添加需求的代碼時(shí)候就這些,其中關(guān)于業(yè)務(wù)實(shí)體類通過ISession會(huì)話操作數(shù)據(jù)庫的代碼就不再給出。相信只要了解Nhibernate基礎(chǔ)只是的都能知道是如何操作的。
說了這么多,多對多的映射到這就說完了。我個(gè)人覺得多對多的問題也就是通過中間結(jié)構(gòu)構(gòu)成的多對多。假如在本例中,我們要完成上述例子中的添加需求,能不能不通過多對多的關(guān)系操作呢?我覺得一點(diǎn)問題也沒有。因?yàn)閷tudet表與SelectCourse表,它們對應(yīng)的實(shí)體關(guān)系之間就是一對多的關(guān)系。同樣對SelectCourse實(shí)體與Course實(shí)體,它們之間也是一對多的關(guān)系。如果我們把Student與Course的關(guān)系分開來看,其實(shí)就是兩個(gè)一對多的過程。通過一對多的關(guān)系也可以解決。
總結(jié):多對多的關(guān)系是Nhibernate映射配置中比較難也比較繞的一部分【我個(gè)人覺得】。但是只要理解其中key和many-to-many各自配置的作用,以及為何是通過這樣配置的,問題也就迎刃而解了。
就寫到這了,希望對各位有所幫組,若有理解或者表述有誤的也希望大俠們踴躍拍磚!

浙公網(wǎng)安備 33010602011771號(hào)