I have a question similar to @ManyToMany without join table (legacy database) with an additional issue.
I have two tables A and B
Awith a multiple column primary key (IDandID2)Bwith a multiple column primary key (IDandID3)
An row in A can reference several rows in B (B.ID = A.ID) and a row in B can be referenced by several rows in A.
EDIT: the database is a read-only legacy database that I cannot change. I do not need to map the relationships with JPA (I could just do it in my program logic with additional selects) but it would be nice.
It is basically a many-to-many relationship without a join table. Since, as for the linked question, I just have to read the tables, I tried with two one-to-many relationships in both classes.
The additional problem that I have is that both IDs used for the join are not the primary key.
I have the following classes:
@Entity
@Table( name = "A" )
@IdClass( PrimaryKeysA.class )
public class A {
@Id
@Column( name = "ID", insertable = false, updatable = false, columnDefinition = "char" )
private String id;
@Id
@Column( name = "ID2", insertable = false, updatable = false )
private int id2;
@OneToMany( cascade = CascadeType.ALL )
@JoinColumn( name = "ID", columnDefinition = "char", referencedColumnName = "ID" )
private Set< B > setOfBs;
}
@Entity
@Table( name = "B" )
@IdClass( PrimaryKeysB.class )
public class B {
@Id
@Column( name = "ID", insertable = false, updatable = false, columnDefinition = "char" )
private String id;
@Id
@Column( name = "ID3", insertable = false, updatable = false )
private int id3;
@OneToMany( cascade = CascadeType.ALL )
@JoinColumn( name = "ID", columnDefinition = "char", referencedColumnName = "ID" )
private Set< A > setOfAs;
}
Hibernate generates the following error:
Exception while preparing the app : referencedColumnNames(ID) of package.B referencing package.A not mapped to a single property
I don’t really get the message: B.id is referencing a single property in A (A.id).
EDIT: as requested:
public class PrimaryKeysA implements Serializable {
private static final long serialVersionUID = 1L;
private int id1;
private int id2;
// getters/setters/equals/hashcode
}
PrimaryKeysB is similar with id3 instead of id2. Both classes A and B are simplified (anonymized) examples.
You could create a view that would act as join table:
And then map it in JPA as a ManyToMany with AJOINB as join table.
If A.ID2 and B.ID3 were unique by themselves, you wouldn’t even need to map A.ID and B.ID in your JPA beans.