Ok so this is probably a trivial question but I\'m having trouble visualizing and understanding the differences and when to use each. I\'m also a little unclear as to how co
1) The circles are Entities/POJOs/Beans
2) deg is an abbreviation for degree as in graphs (number of edges)
PK=Primary key, FK=Foreign key
Note the contradiction between the degree and the name of the side. Many corresponds to degree=1 while One corresponds to degree >1.
Looks like everyone is answering One-to-many
vs. Many-to-many
:
The difference between One-to-many
, Many-to-one
and Many-to-Many
is:
One-to-many
vs Many-to-one
is a matter of perspective. Unidirectional
vs Bidirectional
will not affect the mapping but will make difference on how you can access your data.
Many-to-one
the many
side will keep reference of the one
side. A good example is "A State has Cities". In this case State
is the one side and City
is the many side. There will be a column state_id
in the table cities
.In unidirectional,
Person
class will haveList<Skill> skills
butSkill
will not havePerson person
. In bidirectional, both properties are added and it allows you to access aPerson
given a skill( i.e.skill.person
).
One-to-Many
the one side will be our point of reference. For example, "A User has Addresses". In this case we might have three columns address_1_id
, address_2_id
and address_3_id
or a look up table with unique constraint on user_id
and address_id
.In unidirectional, a
User
will haveAddress address
. Bidirectional will have an additionalList<User> users
in theAddress
class.
Many-to-Many
members of each party can hold reference to arbitrary number of members of the other party. To achieve this a look up table is used. Example for this is the relationship between doctors and patients. A doctor can have many patients and vice versa.