I’m developing a web app with user accounts. I have three system roles and a couple of users. I’ve implemented it this way (simplified for better understanding):
@Table(name = "user")
public class User {
@Id
private String id;
@Column(name = User.COLUMN_LOGIN)
private String login;
@Column(name = User.COLUMN_PASSWORD)
private String password;
@ManyToMany(cascade = CascadeType.DETACH, fetch = FetchType.EAGER)
@JoinTable(name = "role_to_user",
joinColumns={@JoinColumn(name = "userId")},
inverseJoinColumns={@JoinColumn(name = "roleId")})
private Set<Role> roles = new LinkedHashSet<Role>();
}
@Table(name = "role")
public class Role {
@Id
private String id;
@Column(name = Role.COLUMN_ROLETYPE)
private int roletype;
}
What is the best way to implement date of assignment the role to user and date of ending this assignment ? My thought is to add column startDate and endDate to binding table named role_to_user, but i dont know how to tell it to hibernate 🙂
Is this great idea or is there any better way to do that ?
Thanks, Ondrej
You are right in your design assumptions. Someone said that in real life many-to-many relationships are very rare. You need a third table/object, let’s call it `RoleAssignment’:
Of course some adjustments need to be made in
Userclass:Now you can navigate from
UsertoRoleand filter inactive roles in the meantime.