我确实看到了所有其他类似的问题,但没有一个解决方案能解决我的问题。
我有两个类:Person 和 PersonSynonym。一个人可以有很多同义词。Person 类中的 synonyms 属性如下所示:
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "person_id")
private Set<PersonSynonym> synonyms = Sets.newHashSet();
和 PersonSynonym 类:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
... (getters, setters, equals, hashcode, ...)
如果我只向一个人添加一个同义词,则更新 Person 对象可以正常工作。一旦我尝试添加第二个同义词并尝试更新 person 对象,我就会收到此异常:
Caused by: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [my.package.model.PersonSynonym#6]
id 6 的同义词是已经存在的同义词。显然hibernate试图再次插入现有的......为什么?
更新:
将 JoinColumn 移动到 PersonSynonym 没有帮助,Person:
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "person_id")
private Set<PersonSynonym> synonyms = Sets.newHashSet();
人物近义词:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Long person_id;
@ManyToOne
@JoinColumn(name = "person_id", referencedColumnName = "id", insertable = false, updatable = false)
private Person person;