我已经创建了一个类User(Usuario),我需要与类规则建立关系,但我面临关于关系的问题:
我的班级用户(Usuario):
@Entity
public class Usuario implements UserDetails {
private static final long serialVersionUID = 1L;
@Id
private String email;
private String senha;
@OneToMany(fetch=FetchType.EAGER)
private List<Role> roles = new ArrayList<Role>();
//there are getters, setters and methods of UserDetails
班级角色:
@Entity
public class Role implements GrantedAuthority {
private static final long serialVersionUID = 1L;
@Id
private String nome;
//private TipoRole nome;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
@Override
public String getAuthority() {
// TODO Auto-generated method stub
return this.nome;
}
}
我已在实体Role中插入角色ROLE_ADMIN和ROLE_USER,但数据库不允许每个角色有多个用户
默认情况下,系统中创建的所有用户都是RULE_USER,但只能在第一次使用:
然而,在下一次,数据库不允许记录新用户:
我甚至尝试过使用sql命令:
插入usuario_roles(Usuario_email,nome)值('user@test.com','ROLE_USER');
错误消息:11:42:27插入usuario_roles(Usuario_email,nome)值('user@test.com','ROLE_USER')错误代码:1452。无法添加或更新子行:外键约束失败(mvpnfinance
。usuario_roles
,CONSTRAINT FK_j30w68qri0gjgp8irgyf68kdd
外键(Usuario_email
)参考usuario
(email
))0.125秒
更新
我已经将关系更改为@ManyToMany,如果我直接插入数据库运行良好。但在应用程序中我遇到了其他问题。
HTTP状态500 - 请求处理失败;嵌套异常是javax.persistence.PersistenceException:org.hibernate.exception.ConstraintViolationException:无法执行语句
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:键'PRIMARY'的重复条目'ROLE_USER'
我不知道为什么,但是当我保存一个新Person时,系统会尝试在表Role中插入一个新的ROLE_USER。
我在我的Controller类中找到了导致此错误的序列:
List<Role> roles = new ArrayList<Role>();
Role role = new Role();
role.setNome("ROLE_USER");
roles.add(role);
usuario.setRoles(roles);
如果我删除这些行,系统不会将该角色记录到ManyToMany表中。