角色Role与权限Authority,我设计成一对多单向关联,数据库mysql:
//Role.java:
@Entity
public class Role implements Serializable {
private Integer roleid;
private String rolename;
private String description;
private Set<Authority> auths = new HashSet<Authority>();
@Column
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Id
@GeneratedValue
public Integer getRoleid() {
return roleid;
}
public void setRoleid(Integer roleid) {
this.roleid = roleid;
}
@Column
public String getRolename() {
return rolename;
}
public void setRolename(String rolename) {
this.rolename = rolename;
}
//一对多单向关联
@OneToMany(cascade = CascadeType.REFRESH, fetch=FetchType.EAGER)
@JoinTable(name = "role_auth", joinColumns = @JoinColumn(name = "roleid"),
inverseJoinColumns = @JoinColumn(name = "authorityid"))
public Set<Authority> getAuths() {
return auths;
}
public void setAuths(Set<Authority> auths) {
this.auths = auths;
}
// 添加权限
public void addAuth(Authority auth) {
this.auths.add(auth);
}
@Override
public int hashCode() {
...
}
@Override
public boolean equals(Object obj) {
...
}
}
//Authority.java:
@Entity
public class Authority implements Serializable {
private Integer authorityid;
// 范围
private Range range;
// 动作
private Action action;
public Authority() {}
public Authority(Range range, Action action) {
this.range = range;
this.action = action;
}
@ManyToOne
@JoinColumn(name="actionid",
referencedColumnName="actionid")
public Action getAction() {
return action;
}
public void setAction(Action action) {
this.action = action;
}
@Id
@GeneratedValue
public Integer getAuthorityid() {
return authorityid;
}
public void setAuthorityid(Integer authorityid) {
this.authorityid = authorityid;
}
@ManyToOne
@JoinColumn(name="rangeid",
referencedColumnName="rangeid")
public Range getRange() {
return range;
}
public void setRange(Range range) {
this.range = range;
}
@Override
public int hashCode() {
...
}
@Override
public boolean equals(Object obj) {
...
}
}
生成的中间表为role_auth,查看建表语句:
mysql> show create table user_role; | Table | Create Table | user_role | CREATE TABLE `user_role` ( `userid` int(11) NOT NULL, `roleid` int(11) NOT NULL, PRIMARY KEY (`userid`,`roleid`), UNIQUE KEY `roleid` (`roleid`),//roleid为什么具有唯一性??? KEY `FK143BF46A889EC6EB` (`userid`), KEY `FK143BF46A83497181` (`roleid`), CONSTRAINT `FK143BF46A83497181` FOREIGN KEY (`roleid`) REFERENCES `role` (`rol eid`), CONSTRAINT `FK143BF46A889EC6EB` FOREIGN KEY (`userid`) REFERENCES `user` (`use rid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 | 1 row in set (0.00 sec)
如上红色部分,roleid具有唯一性,这样我在插入角色时就会出现类似“Duplicate entry '2' for key 2”的错误。
该怎么改呢??