When mapping many-to-many relationships in JPA, configuration for the table used for the joining foreign-keys can be provided using the @JoinTable
annotation:
@Entity
public class EntityA {
@Id
@Column(name="id")
private long id;
[...]
@ManyToMany
@JoinTable(name="table_join_A_B",
joinColumns=@JoinColumn(name="id_A"), referencedColumnName="id"
inverseJoinColumns=@JoinColumn(name="id_B", referencedColumnName="id"))
private List<EntityB> entitiesB;
[...]
}
@Entity
public class EntityB {
@Id
@Column(name="id")
private long id;
[...]
}
In this example, which consists of EntityA having a many-to-many relation to EntityB, realized by the entitiesB
field, we use the @JoinTable annotation to specify that the table name for the join table is table_join_A_B
, composed by the columns id_A
and id_B
, foreign keys respectively referencing column id
in EntityA's table and in EntityB's table; (id_A,id_B)
will be a composite primary-key for table_join_A_B
table.