• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Entire row as composite key

 
PaulN Pearson
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is a statement of my problem in simplified terms:

I have a User class. An instance of this represents a user of my application.

Each user has attributes such as userId, username, email address etc. The userId is the primary key for the USERS table.

Each user also has a List of roles, which is really just a list of Strings (such as "admin", data-migrator", etc). I have a USER_ROLES table, which has only two columns, USER_ID and ROLE. Since a user may have multiple roles, the primary key for USER_ROLES must be made up of both the USER_ID and the ROLE.

I have worked out how to do this by having a UserRole class, which has an embedded id class, whose attributes are the user id and the role. Is this the only way to do it? It seems a little pointless having a class whose only attribute is another class which contains the fields I want to persist. I appreciate that this would be sensible if there were other columns on my USER_ROLES table which did not form part of the primary key.

Any help in this would be much appreciated.

 
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper
Posts: 4968
1
Hibernate Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Essentially, you're just mapping a many-to-many relationship, aren't you?

You need the join table, but you don't need a class for it. Just use the ManyToMany option.

Check out this tutorial and see if it sheds any light on the situation:

Mapping Many To Many Associations with Hibernate and JPA

-Cameron McKenzie
 
PaulN Pearson
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, of course! I hadn't appreciated that this was in fact a many to many relationship. In fact, because I don't need my Role class to hold a list of users, I was able to map this as a one to many, but still using a join table. Many thanks for your help.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic