In short
JPA documentation says that CollectionTable.joinColumns property is "The foreign key columns of the collection table which reference the primary table of the entity."
Can I make it reference not the primary key column of the entity table, but another column which has unique values?
Details
There is a legacy database with following tables (simplified):
staff:
user_id (int)
user_name (varchar, primary key)
staff_privileges:
id_user (int)
privileges_id (int)
privileges_status (boolean)
Now I'm introducing Hibernate into the project and trying to map this tables to the entity:
@Entity
@Table(name = "staff")
public class User {
@Column(name = "user_id")
private Integer userId;
@Id
@Column(name = "user_name")
private String userName; // primary key column (legacy, cannot be changed)
@ElementCollection
@CollectionTable(name = "staff_privileges", joinColumns = @JoinColumn(name = "id_user"))
@MapKeyColumn(name = "privileges_id")
@Column(name = "privileges_status")
private Map<Integer, Boolean> privileges; // privilegeId <-> isEnabled
}
Won't work because @CollectionTable creates reference to primary key: staff_privileges.id_user -> staff.user_name (primary key)
.
It should be: staff_privileges.id_user -> staff.id_user
.
Is there way to override this reference? Are there any Hibernate or JPA annotations for this? I would like to keep things simple and not introduce any new Entity or Embeddable if possible.