Hibernate: many-to-many relationship table as entity

前端 未结 1 1749
不知归路
不知归路 2021-01-19 22:39

The question is in title:

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

相关标签:
1条回答
  • 2021-01-19 23:09

    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...

    0 讨论(0)
提交回复
热议问题