含有关系的表指的是像学生这样,除了保存学生的基本信息,还希望把选课信息保存到学生的类中。这样情况下不能用软件来辅助产生对应的类和XML,这是NHibernate中唯一需要费脑筋学的地方。学生表对应的类和XML如下所示:
类文件(Student.cs) using System; using Iesi.Collections; namespace CodeTest{ public class Student{ private int studentId; private string studentName; private string studentPassword; private string emailAddress; private DateTime dateCreated; private ISet courses = new HashedSet(); public int StudentId{ get { return studentId; } set { studentId = value; } } public string StudentName{ get { return studentName; } set { studentName = value; } } public string StudentPassword{ get { return studentPassword; } set { studentPassword = value; } } public string EmailAddress{ get { return emailAddress; } set { emailAddress = value; }} public DateTime DateCreated{ get { return dateCreated; } set { dateCreated = value; }} public ISet Courses{ get{return courses;} set{courses=value;} } } } |
XML文件(Student.hbm.xml) <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.0"> <class name="NHibernateTest.Student, NHibernateTest" table="Student"> <id name="StudentId" column="StudentId" type="Int32"> <generator class="native" /> </id> <property name="StudentName" column= "StudentName" type="string" length="40"/> <property name="StudentPassword" type="string" length="20"/> <property name="EmailAddress" type="String" length="40"/> <property name="DateCreated" type="DateTime" length="8"/> <set name="Courses" table="StudentCourse" inverse="false"> <key column="StudentID"/> <many-to-many column="CourseID" class=" NHibernateTest.Course, NHibernateTest "/> </set> </class> </hibernate-mapping> |