Many-to-many with composite key in JPA Spring Java

  Kiến thức lập trình

I have this two entities:

@Entity
public class A implements Serializable{
 
 @Id
 @Column(name = "idA")
 String idA;

 @Column(name = "idB")
 String idB;


//Getters, setters, equals, hash...

}


@Entity
@IdClass(BPK.class)
public class B implements Serializable{
 
 @Id
 @Column(name = "idB")
 String idB;

 @Id
 @Column(name = "idB2")
 String idB2;

 @Id
 @Column(name = "idB3")
 String idB3;

 @Id
 @Column(name = "idB4")
 String idB4;


//Getters, setters, equals, hash...

}

Im trying to implement a ManyToMany relationship between these two entities in many ways, and I’ve gotten an error with every thing’ve tried.

I would like to do something like this:

@Entity
public class A implements Serializable{
 
 @Id
 @Column(name = "idA")
 String idA;

 @Column(name = "idB")
 String idB;

 @ManyToMany
 JoinColumn(name = "idB", referencedColumn = "idB")
 List<B> b;


//Getters, setters, equals, hash...

}

But this way of implementing this relationship only ends up in retrieving a null whenever I go for a getB(). I’ve tried many things and none of them have worked so far. How would be the correct and working form of implementing this many-to-many relationship?

New contributor

Luis Santiyán García is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT