Hibernate拆分多对多关系
现在需要将一个多对多的关系拆分,比如学生和老师之间的关系,拆成两个多对一,并且中间表也需要实体类、配置文件。我大概是这样做的:
学生表:
<hibernate-mapping default-lazy="false">
<class name="Student" table="t_stutent">
<id name="id" type="long">
<column name="ID" precision="20" scale="0"/>
<generator class="sequence">
<param name="sequence">SEQ_STUTENT</param>
</generator>
</id>
<set name="Teacher" inverse="true" lazy="false" cascade="all-delete-orphan">
<key column="STUTENT_ID"/>
<one-to-many class="StudentTeacher"/>
</set>
</class>
</hibernate-mapping>
教师表:
<hibernate-mapping default-lazy="false">
<class name="Teacher" table="t_teacher">
<id name="id" type="long">
<column name="ID" precision="20" scale="0"/>
<generator class="sequence">
<param name="sequence">SEQ_TEACHER</param>
</generator>
</id>
<set name="stutent" inverse="true" lazy="false" cascade="all-delete-orphan">
<key column="TEACHER_ID"/>
<one-to-many class="StutentTeacher"/>
</set>
</class>
</hibernate-mapping>
中间表(即StutentTeacher类对应的表):
<hibernate-mapping default-lazy="false">
<class name="StutentTeacher" table="t_stu_tea">
<id name="id" type="long">
<column name="ID" precision="20" scale="0"/>
<generator class="sequence">
<param name="sequence">SEQ_STU_TEA</param>
</generator>
</id>
<property name="studentId" type="long">
<column name="STUTENT_ID" precision="20"/>
</property>
<many-to-one name="stutent" class="Stutent" fetch="select" insert="false" update="false">
<column name="STUTENT_ID"/>
</many-to-one>
<property name="teacherId" type="long">
<column name="TEACHER_ID" precision="20"/>
</property>
<many-to-one name="teacher" class="Teacher" insert="false" update="false" fetch="select">
<column name="TEACHER_ID"/>
</many-to-one>
</class>
</hibernate-mapping>
现在问题是在保存、删除的时候,没有什么问题,中间表中的记录都已经写入了。但是在前端做更新操作时有问题,举例说明,比如stutent1中保存了teacher1,我在前端更新stutent1中为teacher2,这时没问题;但当我更新后希望的是stutent1中保存teacher1和teacher2,这时候就有问题了,它会报:
“
org.springframework.orm.hibernate3.HibernateSystemException: A collection with cascade="all-delete-orphan" was no longer reference