標籤:關聯 back 這一 font 實體 set .com html 配置
1、引言
老譚在面試開發人員的時候,為了考察他們的資料庫開發能力,經常祭出我的法寶,就是大學資料庫教程中講到的一個模式:學生選課。這個模式是這種:
在這個模式中,學生(Student)和課程(Course)都是實體。分別有主鍵Id。考試成績(Score)是學生和課程之間的多對多關係。
基於這個模式,對於新手,能夠出一些簡單查詢要求,對於熟手,能夠出一些複雜的查詢要求,用起來得心應手。
但今天要說的重點是。怎麼用NHibernate實現這個模式。和一般多對多關係稍有不同的是,這個關係帶有一個屬性,就是考試成績(Score)。
假設多對多關係上帶有屬性,我們通常會把這個關係擴充為實體。也就是把一個多對多關係轉換為一個實體加上兩個多對一關聯性。
假設多對多關係上有多個屬性,將其轉換為一個實體還是有必要的,但僅僅有非常少的屬性(本例中僅僅有一個),轉換為實體實在有些浪費。由於普通情況下,對於實體,我們要為其建立一個人工主鍵,有了人工主鍵,又要建立一個序列。在映射時,這個實體自然要有相應的類。這一大堆事情,想想就非常麻煩。
問題的關鍵是。在概念上這本來就是一個關係,為了實現的方便,而將其轉換為一個實體。這個憑空多出來的實體。使概念變得複雜。很彆扭。
因此,這裡要探究一下,讓關係恢複為為關係,怎麼用NHibernate來處理。
2、映射
假設關係表Score中沒有Score那個屬性欄位,Student實體能夠映射為這種類:
public class Student{ public virtual long Id { get; set; } public virtual string Name { get; set; } public virtual IList<Course> Courses { get; set; }}
Course也類似。
但有了屬性Score,再這樣映射就把這個屬性丟了。為了帶上Score屬性,兩個實體應該這樣映射:
public class Student{ public virtual long Id { get; set; } public virtual string Name { get; set; } public virtual IDictionary<Course, int> Courses { get; set; }}
public class Course{ public virtual long Id { get; set; } public virtual string Name { get; set; } public virtual IDictionary<Student, int> Students { get; set; }}
原來的列表(List)變成了字典(Dictionary),字典的主鍵是原來列表中的元素,值則是關係上的屬性值,即考試成績。
相應的對應檔自然也要調整,結果例如以下:
...<class name="Course" table="Course"> <id name="Id" unsaved-value="0"> <column name="Id" /> ... </id> <property name="Name"> <column name="Name"/> </property> <map name="Students" table="Score" lazy="true"> <key column="CourseId"/> <index-many-to-many column="StudentId" class="Student" /> <element column="Score" /> </map></class>
...<class name="Student" table="Student"> <id name="Id" unsaved-value="0"> <column name="Id" /> ... </id> <property name="Name"> <column name="Name"/> </property> <map name="Courses" table="Score" lazy="true"> <key column="StudentId"/> <index-many-to-many column="CourseId" class="Course"/> <element column="Score" /> </map></class>
經過這種映射。多對多關係中的屬性帶到了類中,並且避免了為關聯建立實體——沒有Score這種類。對這樣映射結果的操作,和常規多對多關係映射方式多產生的基本類似。但也有幾個要注意的問題。
3、查詢
對於一些簡單的查詢,如:
都比較easy處理,由於這僅僅須要在一個實體上加過濾條件。
假設須要在兩個實體上加過濾條件,如查詢小明化學課的成績,就有些複雜。其查詢語句Hql是這種:
select score from Course c, Student s join c.Students score where c.Name=‘化學‘ and index(score) = s.Id and s.Name=‘小明‘
這裡出現了我們非常少用到的hql函數:index()。這是專門應對map的,其目的是獲得map的索引欄位。
弔詭的是。儘管我們指明,map的key是對象。如Course.Students的key是Student的對象,但index()的結果,仍然是 <index-many-to-many column="..." class="..."/> 中 column欄位的值。在上面的查詢中。index(score),我們期望的結果是Student對象,但結果卻是對象的Id。因此。在查詢語句中,我們不得不關聯上Student s,並利用 s.Name 進行過濾。
即便是“簡單的查詢”,如查詢小明全部課程的成績,也有一個問題要注意。
這個問題和懶載入相關。
在這個查詢中。我們已經知道須要擷取全部課程。因此,希望進行預先載入:
from Student s join fetch s.Courses coursewhere s.Name=‘小明‘
得到結果後,假設脫離查詢的環境,如釋放Session,在訪問課程時,如:
s.Courses.Select(c => c.Key.Name)
仍會拋出異常。由於,上述的查詢並沒有把Course對象載入進來。
眼下還不知道怎麼預載入map中索引對象。
須要的話,僅僅有依賴懶載入機制。
4、維護
除了查詢,在對關係進行維護時,也有一點值得特別注意:save-update類型的cascade無效。
cascade屬性,為我們進行關係維護帶來不少便利。
在常規(不帶屬性)的多對多關係中。我們的維護操作能夠是這種:
小明選化學課:
using (var tx = session.BeginTransaction()){ var student = GetStudent(studentName) ?? new Student { Name = studentName, Courses = new List<Course>() }; var course = GetCourse(courseName) ?? new Course { Name = courseName, Students = new List<Student>() }; if (!course.Students.Contains(student)) { course.Students.Add(student); } session.SaveOrUpdate(course); tx.Commit();}
當中,GetStudent(studentName) 和 GetCourse(courseName) 各自是指,依據學生名字或課程名字從資料庫中載入對應對象。
在上面的程式碼片段中,假設資料庫中沒有,則建立。
維護關係後,進行儲存。
須要注意的是,在儲存 course 的時候,並沒有確保 student 是一個持久化的對象。假設student尚未被持久化,則在儲存時,NHibernate會自己主動儲存。並維護和course的關係。可以這麼做。依賴於Course中關係上的cascade屬性定義(第三行末尾):
<class name="Course" table="Course"> ... <bag name="Students" table="Scoure" lazy="true" cascade="save-update"> <key column="CourseId"/> <many-to-many column="StudentId" class="Student" /> </bag> </class>
但在包括屬性的多對多關係上。因為要使用map。就無法進行這種配置——配置了也不生效。
假設資料庫中尚未儲存該學生。我們不得不首先建立並將其持久化(第7行):
using (var tx = session.BeginTransaction()){ var student = GetStudent(studentName); if (student == null) { student = new Student {Name = studentName, Courses = new Dictionary<Course, int>()}; session.Save(student); } var course = GetCourse(courseName) ?? new Course {Name = courseName, Students = new Dictionary<Student, int>()}; if (course.Students.ContainsKey(student)) { course.Students[student] = score; } else { course.Students.Add(student, score); } session.SaveOrUpdate(course); tx.Commit();}
否則,就等著NHibernate拋出異常吧。
5、結論
用Map/Dicitionary表達的多對多關係,要比用Bag/List所表達的,操作起來更為複雜。
但這種代價。我們樂意承擔。
這是由於。我們更看重模型設計,更重視概念完整性。是模型決定詳細實現,而不是反過來。依據詳細實現來改動模型的設計。
??
用NHibernate處理帶屬性的多對多關係