更新多对多的属性

时间:2012-12-10 10:17:43

标签: hibernate many-to-many hibernate-mapping hbm

我通过 StudentCourse 连接表学生课程之间的多对多关联。 StudentCourse 有一个名为 grade 的额外属性。 为了让学生能够访问特定课程的成绩,我在 Student.hbm.xml 中写了以下映射:

<map name="coursesGrades" table="StudentCourse" lazy="false" cascade="save-update" inverse="true">
    <key column="studentId" />
    <map-key-many-to-many class="Course" column="courseId" />
    <element type="integer" column="grade" />
</map>

获取数据时,一切似乎都很棒。但是,在尝试更新成绩时,我会遇到唯一约束违反异常,因为hibernate不是更新行,而是尝试插入一个具有相同studentId和courseId的新行(定义为唯一的)。

所以我的问题是:如何让hibernate通过studentId和courseId更新地图?

StudentCourse.hbm.xml 如下所示:

<class name="StudentCourse" table="StudentCourse"...>       
        <composite-id name="pk" class="StudentCoursePK">
            <key-many-to-one name="Student" column="studentId"/>
            <key-many-to-one name="Course" column="courseId"/>
        </composite-id>
        <property name="grade" type="integer"/>         
</class>

任何帮助都会得到满足。

1 个答案:

答案 0 :(得分:0)

由于您为 coursesGrades 地图设置了倒数true,表示学生不是此关系的所有者,因此不会更新成绩。您如何准确更新数据?另外我不明白你的 StudentCourse 类映射,是不是学生中定义的映射足以映射StudentCourse表?

相关问题