Hibernate:作为实体的多对多关系表 [英] Hibernate: many-to-many relationship table as entity

查看:110
本文介绍了Hibernate:作为实体的多对多关系表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题在于:



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

解决方案

我会说,你的问题非常合理。看看这个文档部分:第24章。最佳实践。提取:


不要使用外来的关联映射:

真正的多对多关联的实际测试案例很少见。您需要存储在link
表格中的附加信息时,最多
。在这种情况下,将两个一对多
关联用于中间链接类会更好。实际上,大多数协会
是一对多和多对一的。因此,在使用任何其他关联风格时,您应谨慎行事


我们正在处理这个问题,是通过引入配对对象。所以,如果有一个员工有很多联系人,我们可以有 EmployeeContact 。这样我们可以获得很多,因为我们可以用更多/新的属性(IsMain,IsActive等)丰富EmployeeContact。在这种情况下,两侧的映射是


  • 员工有一对多(set) EmployeeContacts

  • 联系人具有一对多(set) EmployeeContacts

  • EmployeContact具有多对一(关系)员工

  • EmployeContact具有多对一(关系)联系人

$ b $因此,最后,映射是平常的,但我们可以使用子查询等搜索Employee或Contact。
$ b

注意:在那情况是适合的,如果配对表具有自己的替代密钥,例如EmployeeContactId。它可以随时添加。有身份......


The question is in title:

How can I make many-to-many relationship table as entity?

解决方案

I would say, that your question is very reasonable. Take a look at this doc part: Chapter 24. Best Practices. An Extract:

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.

The way, we are handling that, is by introducing the pairing object. So, if there is an Employee having many Contacts, we can have EmployeeContact. This way we can gain a lot, because we can enrich the EmployeeContact with more/new attributes (IsMain, IsActive etc.)

In this scenario, the mapping on both sides is that

  • Employee has one-to-many (set) EmployeeContacts
  • Contact has one-to-many (set) EmployeeContacts
  • EmployeContact has many-to-one (relation) Employee
  • EmployeContact has many-to-one (relation) Contact

So, at the end, the mapping is usual, but we can search for Employee or Contact using the Subqueries etc.

NOTE: in that case is suitable, if the pairing table has its own surrogated key, e.g. EmployeeContactId. It could be added at any time.. e.g. with identity...

这篇关于Hibernate:作为实体的多对多关系表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆