Use a Composite key of an entity as the ManyToMany key in another entity

Viewed 41

I have the following case, I am trying to do a many to many mapping like a User and all the teams in which the user belongs to.

    Class AID
       private int b
       private int c
    
    @IdClass(AID.class)
    Class A
   
      @Id
      @SequenceGenerator(name = "b_seq", sequenceName = "id_seq", allocationSize = 1)
      @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "b_seq")
      private int b
    
      @Id
      @Column(name = "col_c")
      private int c
    
    Class D
    #need to define a many to many mapping with A here

Assuming class D is the Teams class and class A has a composite key as primary key how would I proceed?

1 Answers

I was using MSSQL and it seems referencedColumnName needs to be actually specified.

So if Class D will be as follows

Class D
 @Id
 private int e
 @ManyToMany
 @JoinTable(
          name = "d_a_info",
          joinColumns = {
              @JoinColumn(name = "e", referencedColumnName = "e"),
          },
          inverseJoinColumns =  {
              @JoinColumn(name = "b", referencedColumnName = "b"),
              @JoinColumn(name = "c", referencedColumnName = "c")
          }
  )
 private Set<A> setOfA= new HashSet<>();

also in AID class i had to amnaually set the getter methods

 @Column(name = "b", nullable = false)
  public String getB() {
    return this.b;
  }

 @Column(name = "c", nullable = false)
  public String getC() {
    return this.c;
  }
Related