Hibernate - 具有相同标识符值的不同对象已与会话关联
将实体的@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
在网络应用程序中没有任何改变。读取实体,然后更改表单中的某些字段,然后在提交后我尝试保存或更新实体。使用 int
作为 @Id
没有问题,但现在使用 String
作为 @Id
我得到了上面的结果更新或保存实体时出错:
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public void saveOrUpdate(User u) {
getHibernateTemplate().saveOrUpdate(u);
}
可能是什么问题?
Possible Duplicate:
Spring + Hibernate : a different object with the same identifier value was already associated with the session
After changing the @id
of a Entity from
@Id
private int getId(){
return this.id;
}
to
@Id
private String getLogin(){
return this.login;
}
I get the error:
a different object with the same identifier
value was already associated with the session
In the webapplication isn't changed anything. A read the entity and then change some fields in a form and than after submit I tried to save or update the Entity. With the int
as @Id
there was no problem but now with the String
as @Id
I get the above error by update or save the Entity:
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public void saveOrUpdate(User u) {
getHibernateTemplate().saveOrUpdate(u);
}
What could be the problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这意味着您正在尝试保存或更新具有不唯一或设置自动递增标识符的分离对象。
如果你想插入一个新对象,你希望它的id为空或唯一,具体取决于你是否使用自动增量(自动增量为null,非自动增量设置为唯一值),如果你想更新您想确保它附加到上下文。
您可以使用 session.merge(object) 将对象重新附加到上下文,该方法返回对象的附加版本。
换句话说:
如果您尝试插入,请确保配置为 Id 的字段在使用自动增量时为空,或者是唯一的。
如果您尝试更新,请确保已附加该对象。
您可以通过从数据库中选择它(基于您拥有的字段)、进行更改然后更新来完成此操作,或者仅调用 session.merge(object) 方法并接收该对象的附加版本,然后您可以使用该版本也更新。
It means you are trying to save or update a detached object which has an un-unique or set auto-incrementing identifier.
If you want to insert a new object you want it's id to be empty or unique depending on whether you use auto incrementation or not(null for auto incrementation, set with a unique value for non-auto-incrementation), if you want to update it you want to make sure it is attached to the context.
You can reattach an object to the context using session.merge(object) which returns an attached version of the object.
In other words:
If you are trying to insert make sure the field that is configured as Id is either null if you use auto incrementation or is unique.
If you are trying to update make sure the object is attached.
You can do this by selecting it from your database (based on the fields you have), make the changes, and then update, or just call the session.merge(object) method and receive an attached version of the object which you can then also update.