我有一个奇怪的问题,我无法真正解决。这是一个例外:
javax.persistence.EntityExistsException: a different object with the same identifier value was already associated with the session: [com.mycompany.Employee#101]
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1359) [hibernate-entitymanager-4.2.2.Final.jar:4.2.2.Final]
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1310) [hibernate-entitymanager-4.2.2.Final.jar:4.2.2.Final]
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1316) [hibernate-entitymanager-4.2.2.Final.jar:4.2.2.Final]
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:881) [hibernate-entitymanager-4.2.2.Final.jar:4.2.2.Final]
例外很明显,持久性上下文中有一个对象阻止我persist
通过。问题是:Employee
上下文中根本没有(用调试器检查)!
但是,有一个Talent
我想更新的实例也是一个Employee
. 它们是这样相关的:
一个人:
public class Person {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "person")
private Set<PersonRole> roles = new LinkedHashSet<>();
}
有很多角色:
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class PersonRole {
@Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "personrolegen")
@SequenceGenerator(name = "personrolegen", sequenceName = "person_role_id_seq")
protected Long id;
@MapsId
@ManyToOne(optional = false)
protected Person person;
}
和两者都Talent
扩展Employee
(PersonRole
在那里没有什么特别的)。
当一个人已经是人才并且我使用现有人员的引用构造一个员工并调用
entityManager.persist(new Employee(person))
现在 @Id 映射PersonRole
看起来不太好,有人可以确认这是导致上述异常的问题吗?我怎样才能做得更好?
我想表达的是,每个角色都附有一个人,它唯一地标识了该角色的子实例。查看 Persistence Context 似乎 Hibernate 正在使用PersonRole#person.id
as EntityKey
,这似乎导致了异常。