Summary on 20080706: setting for many-to-many mapping in hibernate

本文介绍Hibernate中多对多关系的实现方法,通过班级与教师的关系为例,讲解了如何进行多对多关系的映射及配置文件的写法,并强调了在保存和删除记录时的操作顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值