我確實看到了所有其他類似問題,但沒有一個解決方案解決了我的問題。休眠:具有相同標識符值的不同對象已與會話相關聯
我有兩個類:Person和PersonSynonym。一個人可以有很多同義詞。在Person類的同義詞屬性看起來是這樣的:
@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對象,如果我只追加1個代名詞了一個人正常工作。當我嘗試添加第二個同義詞,嘗試更新的人對象我得到這個異常:
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是一個現有的已經。顯然冬眠試圖再次插入現有的...爲什麼?
更新:
移動JoinColumn到PersonSynonym沒有幫助,聯繫人:
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "person_id")
private Set<PersonSynonym> synonyms = Sets.newHashSet();
PersonSynonym:
@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;
雖然它可能沒有解決問題的根源,但您是否嘗試過不同的GenerationType策略?如果你這樣做會發生同樣的錯誤嗎? –
我做了,沒有區別。 –