我有一个对象,其中包含对象列表。
我需要检索对象,删除其所有项目,添加更新的项目并在数据库中更新它,但是当我尝试更新列表时,它会遇到以下错误。
org.hibernate.NonUniqueObjectException: a different object with the same
identifier value was already
associated with the session
代码
...
temporary.getItems().get(1).setName("P1");
temporary.getItems().get(2).setName("P2");
//retrieve selected user's object
User user = (User) session.get(User.class, user.getId());
//remove all of its items
user.getItems().clear();
//add updated items
//(same as items that has been removed but with new values)
user.getItems().addAll(temporary.getItems());
//persist new items
for (int i = 0; i < user.getItems().size(); i++) {
session.update(user.getItems().get(i));
}
//update the object
session.update(user);
tx.commit();
实体
public class User {
@Id
@GeneratedValue
private long id;
@OneToMany
@LazyCollection(LazyCollectionOption.FALSE)
private List<UserItem> items;
...
}
public class UserItem {
private Long id;
....
}
最佳答案
发生异常是因为您有 2 个对象具有相同的标识符(主键)。因此,我建议您在实体类中的 id 属性中添加注释 @GenerateValue。顺便说一句,您可以应用级联来持久化您的对象(cascade tutorial)
关于java - 如何更改列表的值并在 hibernate 中更新列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19802799/