For n-n relationship in database, hibernate supplies the many-to-many mapping type. let's take the class and teacher relation as the example; one class can have different teachers, and also, one teacher can work for different classes, this is one n-n relationship.
teacher: teacher_id class: class_id class_teacher: class_id,teacher_id; So for the mapping file of class, for the set of 'Teacher', mapping should be like: <set name="teachers" table="class_teacher" inverse="false"> <key column="class_id"/> <many-to-many column="teacher_id" class="Teacher"> </set>
Seen from the code, the following should be noted: 1. there is no 'cascade' setting, but when save/update/delete class, the record in class_teacher will be saved/updated/deleted. 2. if inverse = false, this class will be responsible to keep the relation table 3. use <many-to-many> to define the related table:teacher
Another note about the key setting in the table: class_id,teacher_id by default, it's one composite-key of (class_id,teacher_id), but also, they are the foreign keys, they can be null. However, when you set the primay key, you can check that class_id, teacher_id can't be null.
And next, let's focus on the order when save/delete: 1.Save save class to db, save class_teacher record into db 2. Delete deleterecord of class_teacher first and then delete class.