jpa Relations between entities Multiplicity in Entity Relationships


Example

Multiplicity in Entity Relationships

Multiplicities are of the following types:

  • One-to-one: Each entity instance is related to a single instance of another entity.
  • One-to-many: An entity instance can be related to multiple instances of the other entities.
  • Many-to-one: multiple instances of an entity can be related to a single instance of the other entity.
  • Many-to-many: The entity instances can be related to multiple instances of each other.

One-to-One Mapping

One-to-one mapping defines a single-valued association to another entity that has one-to-one multiplicity. This relationship mapping use the @OneToOne annotation on the corresponding persistent property or field.

Example: Vehicle and ParkingPlace entities.

One-to-Many Mapping

An entity instance can be related to multiple instances of the other entities.

One-to-many relationships use the @OneToMany annotation on the corresponding persistent property or field.

The mappedBy element is needed to refer to the attribute annotated by ManyToOne in the corresponding entity:

 @OneToMany(mappedBy="attribute")

A one-to-many association needs to map the collection of entities.

Many-to-One Mapping

A many-to-one mapping is defined by annotating the attribute in the source entity (the attribute that refers to the target entity) with the @ManyToOne annotation.

A @JoinColumn(name="FK_name") annotation discribes a foreing key of a relationship.

Many-to-Many Mapping

The entity instances can be related to multiple instances of each other.

Many-to-many relationships use the @ManyToMany annotation on the corresponding persistent property or field.

We must use a third table to associate the two entity types (join table).