Hi Experts,
I have a very classic Student, Teacher & Course problem and I would like to know why SaveorUpdateCopy behaves like this. BTW, I have really read gonzao's article
http://hibernar.org/articulos_en/persis ... ethods.phpThe classes are very simple. I just post their XML
<class name="Teacher" table="Teacher" lazy="false">
<id name="Teacher_Id" column="Teacher_Id" type="Int32">
<generator class="native"/>
</id>
<property name="Teacher_Name" column="Teacher_Name" type="String" not-null="true" />
<set name="Courses" lazy="true" inverse="true" cascade="save-update" >
<key>
<column name="Teacher_Teacher_Id"/>
</key>
<one-to-many class="Course"/>
</set>
</class>
<class name="Student" table="Student" lazy="false">
<id name="Student_Id" column="Student_Id" type="Int32">
<generator class="native"/>
</id>
<property name="Student_Name" column="Student_Name" type="String" not-null="true" />
<set name="Courses" lazy="true" inverse="true" cascade="save-update" >
<key>
<column name="Student_Student_Id"/>
</key>
<one-to-many class="Course"/>
</set>
</class>
<class name="Course" table="Course" lazy="false">
<id name="Course_Id" column="Course_Id" type="Int32">
<generator class="native"/>
</id>
<property name="Course_Name" column="Course_Name" type="String" not-null="true" />
<many-to-one name="Student" class="Student" >
<column name="Student_Student_Id"/>
</many-to-one>
<many-to-one name="Teacher" class="Teacher" >
<column name="Teacher_Teacher_Id"/>
</many-to-one>
</class>
The unit test:
Configuration configuration = new Configuration();
configuration.Configure(Assembly.GetExecutingAssembly(), "hibernate.cfg.xml");
configuration.AddAssembly("Business");
ISessionFactory factory = configuration.BuildSessionFactory();
ISession sess = factory.OpenSession();
sess.Transaction.Begin();
Student studentA = new Student("Peter");
Teacher teacherA = new Teacher("John");
sess.Save(teacherA);
sess.Save(studentA);
Course courseA = new Course("Physics");
courseA.Student = studentA;
courseA.Teacher = teacherA;
studentA.Courses.Add(courseA);
teacherA.Courses.Add(courseA);
sess.SaveOrUpdateCopy(teacherA);
sess.Transaction.Commit();
When I break at the SaveOrUpdateCopy statement, both studentA.Courses & teacherA.Courses are transient (no ID). After executing the SaveOrUpdateCopy statement, I got the following inconsistent session objects:
studentA.Courses -> still transient
teacherA.Courses -> became persistent (have a generated ID and inserted into DB)
After transaction commit, studentA.Courses was also persisted but with a different ID. As expected, there are two (duplicated) Physics courses in the DB.
I know that SaveOrUpdateCopy is totally unnecessary and removing it will fix the problem. However, I expect that this extra line should only affect the performance, not the end result!
Hopes someone can help.
Regards,
Michael Leung