I have a 'User' class:
Code:
public class User implements Serializable {
@Id
@GeneratedValue
int id;
String nome;
@Column(unique = true)
String email;
@ManyToMany
@JoinTable (name = "user_roles", joinColumns=
{ @JoinColumn (name = "user_id")}, inverseJoinColumns=
{ @JoinColumn (name = "role_id")})
private List<Role> roles;
I have a 'Role' class:
Code:
public class Role implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
int id;
@Column(unique = true)
String role;
**Relationship** :An User has roles, and roles has users. I have a many-to-many relationship here. The relation is unidirectional, and my dominant entity is User.
In my database has a table named "user_roles", created automatically. I have a User registered with two roles.
When I retrieve the User from my database using a "UserDao" class, and I try to access the roles of the user, I get NullPointerException. I got all others informations (name, email, etc), but the roles I can not access.
I tried using iterator:
Code:
List roles = user.getRegras();
for (Iterator it = roles.iterator(); it.hasNext();){
Role r = (Role) it.next();
out.println("Role:" + r.getRole());
}
I tried to instantiate the variable "roles" in the 'User' class like below. But every time the variable returns size 0:
Code:
@ManyToMany
@JoinTable (name = "user_roles", joinColumns=
{ @JoinColumn (name = "user_id")}, inverseJoinColumns=
{ @JoinColumn (name = "role_id")})
private List<Role> regras = new ArrayList<Role>();
I tried getting the roles from Object User, but I receive a NullPointerException when the method size() is called.
Code:
List<Role> roles = (List<Role>)user.getRoles();
out.println("size roles: " + roles.size());
I'm trying to acess my table 'user_roles' to retrieve the data from database, but I can't dothis. Can anyone help me?
Thanks in Advance