我有名为Country,City和People的表。有什么能阻止hibernate保存同一个人对象?这是我的类,问题是当我尝试保存国家/地区对象时,Hibernate会尝试按预期保存或更新相同的人物对象。(City的people对象和Country的people对象具有相同的PK)
org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session
类;
class Country{
.....
@JoinColumn(.....)
@ManyToOne(optional = false, fetch = FetchType.EAGER)
@Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
private City city;
@JoinColumn(.....)
@ManyToOne(optional = false, fetch = FetchType.EAGER)
@Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
private People people;
}
class City{
....
@JoinColumn(.....)
@ManyToOne(optional = false, fetch = FetchType.EAGER)
@Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
private People people;
}
这是我的保存方法;
public void save(){
....
getCurrentSession().saveOrUpdate(customer); //Hibernate session
}
答案 0 :(得分:1)
这里有两个解决方案:
merge
代替save
save
级联注释。使用save
和save
级联基本上告诉Hibernate“请坚持这个新对象以及他所有的新关系”。你不希望这样。