what is onetomany and manytoone 1

what is onetomany and manytoone

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.

In 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 have List skills but Skill will not have Person person. In bidirectional, both properties are added and it allows you to access a Person given a skill( i.e. skill.person).

In One-to-Many the one side will be our point of reference. For example, "A User has an 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 have Address address. Bidirectional will have an additional List users in the Address class.

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

Here is what the above code is Doing:
1. The @Entity annotation is used to mark the class as a JPA entity.
2. The @Id annotation is used to mark the primary key of the entity.
3. The @GeneratedValue annotation is used to specify the primary key generation strategy.
4. The @Column annotation is used to specify the mapped column for a persistent property or field.
5. The @OneToMany annotation is used to define the one-to-many mapping between the source entity and the target entity.
6. The @JoinColumn annotation is used to specify the foreign key column for the one-to-many mapping.
7. The @ManyToOne annotation is used to define the many-to-one mapping between the source entity and the target entity.
8. The @ManyToMany annotation is used to define the many-to-many mapping between the source entity and the target entity.
9. The @JoinTable annotation is used to define the join table for the many-to-many mapping.
10. The @JoinColumns annotation is used to define the composite foreign key columns for the join table.

Similar Posts