I´m trying to map an existing database to Hibernate using annotations.
The problem is as follows.
‘organization’ and ‘organization_roles’ has a many to many relationship which is resolved in a
table ‘organization_has_roles’ using the two primary keys as a composite primary key in the join table.
Next there is a ‘users’ table. Users can have a single role in multiple organizations. This is again resolved in a join table named ‘users_has_organizations_and_role’ which has a composite primary key of the ‘user_id’, ‘organization_id’ and ‘organization_role_id’ and a unique_index on the ‘user_id’ and ‘organization_id’.
The ‘users_has_organizations_and_role’ references the ‘organization_has_roles’ composite primary key(organization_id, organization_role_id) and the users table (user_id)
I have not been able to find examples on this matter that worked.
Is it possible to map this. Which Annotations should I use and how?
I´m using Hibernate 4, although it might not matter..
The main problem with this approach is that you have an unmappable ORM mismatch: you have an entity in your database (
organization_has_roles) which is translated as a relationship in OO. As this relationship is not an entity, and has no@Id, it cannot be referenced into yet another entity.A solution is to map the database entity
organization_has_rolesinto a JPA/Hibernate entity, with either a composite key, or with a synthetic key (whatever you prefer). You can then refer to this entity in yourUsermodel.