问题
The question is in title:
How can I make many-to-many relationship table as entity?
回答1:
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...
来源:https://stackoverflow.com/questions/19687006/hibernate-many-to-many-relationship-table-as-entity