0

I have the next problem: I have a "User" entity with a many to many relationship to "Roles". The thing is, the "Roles" are enumerated (there are always 5 of them) so fetching them whenever i fetch a user seems unnecessary (as they also rarely change). I would like to somehow keep the roles in memory and attach them to the user whenever i bring her. It is worth noting that hibernate has 2nd level cache enabled so i will be able to utilize this if necessary. Does anyone have a solution for this?

thanks in advance

ShinySpiderdude
  • 1,170
  • 4
  • 14
  • 18
  • The answer is in the question, isn't it? Use the second-level cache. (I'm not sure this will make any significant difference though, given that getting a role by ID in a table of 5 rows will already be extremely fast) – JB Nizet Mar 10 '13 at 10:59
  • Moreover you can still cache the association between your role and your user. – benzonico Mar 10 '13 at 15:58

1 Answers1

0

If you can change your data model, drop the table roles and convert your many-to-many table into a simple many-to-one table with a foreign key to users, and a column holding the role (either as varchar or as number, but I would advise using varchar since it is easier to maintain). Then you can map this table as the following:

@Entity
public class UserRole {
    @ManyToOne
    private User user;
    @Column
    @Enumerated(EnumType.STRING) // depends if column is varchar or number
    private Role role;
}

public enum Role { ROLE1, ROLE2, ROLE3, ROLE4, ROLE5 }

Notice that if you don't drop the roles table it is also possible to do this as long as your role id's are 0 to 4, using the EnumType.ORDINAL mapping (which is the default). If they are 1 to 5, add a dummy role at the beginning of the Role enum.

Didier L
  • 18,905
  • 10
  • 61
  • 103
  • But that would effectively create a OneToMany relationship. So the entries will look like ("User1", "Role1") ("User1", "Role2") ("User2", "Role1") i was hoping to avoid that – ShinySpiderdude Mar 10 '13 at 15:53
  • Well yes of course since you have this requirement of assigning several roles to a single user you cannot avoid a one-to-many relationship. You just need to configure some caching to avoid fetching them every time but with this solution you do not need to fetch roles at all which seemed to be what you asked. – Didier L Mar 10 '13 at 21:30