【问题标题】:Hibernate - a different object with the same identifier value was already associated with the session [duplicate]Hibernate - 具有相同标识符值的不同对象已与会话相关联[重复]
【发布时间】:2011-03-16 23:56:49
【问题描述】:

可能重复:
Spring + Hibernate : a different object with the same identifier value was already associated with the session

更改实体的@id来自

@Id
private int getId(){
     return this.id;
}

@Id
private String getLogin(){
     return this.login;
}

我得到错误:

a different object with the same identifier
value was already associated with the session

在 web 应用程序中没有改变任何东西。读取实体,然后更改表单中的某些字段,然后在提交后我尝试保存或更新实体。使用int 作为@Id 没有问题,但现在使用String 作为@Id 我通过更新或保存实体得到上述错误:

 @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
 public void saveOrUpdate(User u) {  
  getHibernateTemplate().saveOrUpdate(u);  
 }

可能是什么问题?

【问题讨论】:

  • 在会话中显示代码可能会有所帮助。

标签: hibernate spring annotations entity validates-uniqueness-of


【解决方案1】:

这意味着您正在尝试保存或更新具有不唯一或设置自动递增标识符的分离对象。

如果你想插入一个新对象,你希望它的 id 是空的还是唯一的,这取决于你是否使用自动递增(自动递增为 null,为非自动递增设置一个唯一值),如果你想要更新它,你要确保它附加到上下文中。

您可以使用 session.merge(object) 将对象重新附加到上下文,它会返回对象的附加版本。

换句话说:

如果您尝试插入,请确保配置为 Id 的字段在您使用自动递增时为空或唯一。

如果您尝试更新,请确保已附加对象。 您可以通过从数据库中选择它(基于您拥有的字段)来执行此操作,进行更改,然后更新,或者只是调用 session.merge(object) 方法并接收对象的附加版本,然后您可以也更新了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-06
    • 2011-01-09
    • 2014-11-17
    • 1970-01-01
    • 2011-04-02
    • 2018-03-26
    • 1970-01-01
    相关资源
    最近更新 更多