问题在标题中:
如何将多对多关系表作为实体?
最佳答案
我想说,你的问题很有道理。看看这个文档部分:Chapter 24. Best Practices 。摘录:
Do not use exotic association mappings:
Practical test cases for real many-to-many associations are rare. Most of the time you need additional information stored in the "link table". In this case, it is much better to use two one-to-many associations to an intermediate link class. In fact, most associations are one-to-many and many-to-one. For this reason, you should proceed cautiously when using any other association style.
我们处理这个问题的方法是引入配对对象。因此,如果一个 Employee
拥有许多 Contact
,我们就可以拥有 EmployeeContact
。这样我们可以获得很多好处,因为我们可以用更多/新的属性(IsMain、IsActive 等)来丰富 EmployeeContact
在这种情况下,双方的映射是
- 员工有
一对多
(设置)EmployeeContacts - 联系人有
一对多
(已设置)EmployeeContacts - EmployeContact 具有
多对一
(关系)Employee - EmployeContact 具有
多对一
(关系)Contact
所以,最后,映射是常见的,但我们可以使用子查询等搜索员工或联系人。
注意:在这种情况下是合适的,如果配对表有自己的代理键,例如员工联系人 ID。它可以随时添加......例如有身份...
关于Hibernate:多对多关系表作为实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19687006/