你好,
我有一个具有多对多关系的用户和角色模型如下
@Entity
@Table(name = "USER")
@Indexed
@XmlRootElement
public class User extends BaseObject implements Serializable, UserDetails, PersistentObject, HasRevision, org.activiti.engine.identity.User {
private Set<Role> roles = new HashSet<Role>();
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "USER_ROLE",
joinColumns = { @JoinColumn(name = "USER_ID") },
inverseJoinColumns = @JoinColumn(name = "ROLE_ID")
)
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
@Entity
@Table(name = "ROLE")
@NamedQueries({
@NamedQuery(
name = "findRoleByName",
query = "select r from Role r where r.name = :name "
)
})
public class Role extends BaseObject implements Serializable, GrantedAuthority {
private Set<User> users = new HashSet<User>();
@ManyToMany(fetch = FetchType.EAGER,mappedBy = "roles")
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
}
当我创建或更新具有角色分配的用户时,异常将如下所示
用户的ID:用户 org.springframework.orm.hibernate4.HibernateOptimisticLockingFailureException:具有标识符[user]的类[com.model.User]的对象:乐观锁定失败;嵌套异常是org.hibernate.StaleObjectStateException:Row被另一个事务更新或删除(或unsaved-value映射不正确):[com.model.User #user] ....
引起:org.hibernate.StaleObjectStateException:Row被另一个事务更新或删除(或unsaved-value映射不正确):[com.model.User #user]
我不能把懒惰而不是急切的提取它会导致一些其他问题(某些地方我无法从会话中获取角色),并且我无法删除它将导致角色删除的反向关系。
所以我如何解决问题的建议是值得欢迎的,并提前感谢。