Hibernate:多对多关系表作为实体

标签 hibernate many-to-many hibernate-mapping

问题在标题中:

如何将多对多关系表作为实体?

最佳答案

我想说,你的问题很有道理。看看这个文档部分: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/

相关文章:

java - JPA-onetomany级联在子表中插入相同的记录两次

java - hibernate 确实很慢。如何让它更快?

hibernate - Play 框架中数据库级别的国际化

MySQL多对多关系问题

java - 在 Hibernate 中使用接口(interface)而不是具体类映射 HashMap

java - 如何使用 ids 插入记录列表?

java - 在生产或测试中运行时,Grails 不使用我的数据源?

mysql - 来自 Laravel 5.5 中 HasManyThrough 的 ManyToMany 关系的 GroupBy 结果

linq-to-sql - Linq2Sql 多对多关系和插入新对象的问题

java - 在 Hibernate 中映射一对多关系?