我有一个对象,其中包含对象列表。
我需要检索对象,删除它的所有项目,添加更新的项目并在数据库上更新它,但是当我尝试更新列表时,它会遇到以下错误。
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;
....
}