many-to-many relation and relational model [closed]

拟墨画扇 提交于 2019-12-25 04:56:24

问题


I learn in Merise or UML if we have tow tables with many-to-many relation we have to create a new table in relational model (in Mysql) and this table will contain the tow id of the tow other tables.
But we really must create a new one because with hibernate and mapping i think we don't need to.
Because each table(entity) will have a list of the other table(entity).
So what's the right way to deal with many-to-many relation ? create a new table or not ?


回答1:


You will still need a 'Join Table' which will contain two columns with foreign keys to the two other tables.

With hibernate, when an entity has a List, you still need to be able to store this relationship on the table.

So for example if you want a many-to-many between TableA and TableB..

//TableA class:    
@ManyToMany
@JoinTable(name="TABLEA_TABLEB",
    joinColumns=
        @JoinColumn(name="TABLEA_ID", referencedColumnName="ID"),
    inverseJoinColumns=
        @JoinColumn(name="TABLEB_ID", referencedColumnName="ID")
    )
public Set<TableB> bees;

//TableB Class: 
@ManyToMany(mappedBy="bees")
public Set<TableA> ays;

This will create a join table with two columns ('tablea_id', 'tableb_id'); Those columns will have a foreign key relationship with the 'ids' (primary keys) of your main entities.




回答2:


Typically you will need to normalise a many to many relationship in a Database, (There are some edge cases where an expert might choose not to). However Spring is not one of these, it just simplifies part of the manual normalisation process.




回答3:


You mentioned UML:

In the case of an Association Class, the join table will have "extra" columns in addition to the keys.



来源:https://stackoverflow.com/questions/21113593/many-to-many-relation-and-relational-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!