Search code examples
javajpamany-to-manyentity

JPA / How to add a property in a ManyToMany relation


I started to create 2 classes for my 2 entities :

  • User : a User may belong to several Group
  • Group : a Group may count several User (members)

The relation between these 2 entities should be bidirectional.

JPA will then create a new relation entity named User-Group. In this table/entity we will find the User PK and the Group PK together.

My problem is : each User in a Group should have a "role". Default role is "member", but a User can also be "leader".

The "role" property doesn't exist in any of my classes and should be associated with the couple "User PK / Group PK" of the User-Group relation table created by JPA.

How can I handle the "role" property as it is not a User property neither a Group property but a User-Group property ? How to add this column in the User-Group table which is a JPA creation ?

Thanx for your help.


Solution

  • The easiest way is to split the Many-to-Many in two One-To-Many relationships towards a new entity : you create a UserRoleInAGroup class containing the role field, a group and a user.

    The 2 resulting One-To-Many relationships are :

    • 1st :
      • Each User can be related to many UserRoleInAGroup
      • Each UserRoleInAGroup is related to a single User
    • 2nd :
      • Each Group can be related to many UserRoleInAGroup
      • Each UserRoleInAGroup is related to a single Group

    I hope it helps.