jpaMany to Many Mapping


Introduction

A ManyToMany mapping describes a relationship between to entities where both can be related to more than one instance of each other, and is defined by the @ManyToMany annotation.

Unlike @OneToMany where a foreign key column in the table of the entity can be used, ManyToMany requires a join table, which maps the entities to each other.

Parameters

AnnotationPurpose
@TableGeneratorDefines a primary key generator that may be referenced by name when a generator element is specified for the GeneratedValue annotation
@GeneratedValueProvides for the specification of generation strategies for the values of primary keys. It may be applied to a primary key property or field of an entity or mapped superclass in conjunction with the Id annotation.
@ManyToManySpecifies relationship between Employee and Project entities such that many employees can work on multiple projects.
mappedBy="projects"Defines a bidirectional relationship between Employee and Project
@JoinColumnSpecifies the name of column that will refer to the Entity to be considered as owner of the association
@JoinTableSpecifies the table in database which will hold employee to project relationships using foreign keys

Remarks

  • @TableGenerator and @GeneratedValue are used for automatic ID creation using jpa table generator.
  • @ManyToMany annotation specifies the relationship between Employee and Project entities.
  • @JoinTable specifies the name of the table to use as join table jpa many to many mapping between Employee and Project using name = “employee_project”. This is done because there is no way to determine the ownership of a jpa many to many mapping as the database tables do not contain foreign keys to reference to other table.
  • @JoinColumn specifies the name of column that will refer to the Entity to be considered as owner of the association while @inverseJoinColumn specifies the name of inverse side of relationship. (You can choose any side to be considered as owner. Just make sure those sides in relationship). In our case we have chosen Employee as the owner so @JoinColumn refers to idemployee column in join table employee_project and @InverseJoinColumn refers to idproject which is inverse side of jpa many to many mapping.
  • @ManyToMany annotation in Project entity shows inverse relationship hence it uses mappedBy=projects to refer to the field in Employee entity.

Full example can be referred here