我有以下简单的设计:
(来源:kawoolutions.com)
这基本上是 JPA 不支持的非不相交继承的一种解决方法。人员可以单独存在,但也可以有一个玩家实体、一个教练实体或两个实体来完成逻辑。
以下是相当容易理解的JPA 2.0映射(注意 @Id 前向关联):
@Entity
@Table(name = "Persons")
public class Person implements Serializable
{
@Id
@Column(name = "id")
private Integer id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@OneToOne(mappedBy = "person")
private Coach coach = null;
@OneToOne(mappedBy = "person")
private Player player = null;
...
}
@Entity
@Table(name = "Players")
public class Player implements Serializable
{
@Column(name = "registration_nbr")
private String registrationNbr = null;
@Id
@OneToOne
@JoinColumn(name = "id")
private Person person = null;
...
}
@Entity
@Table(name = "Coaches")
public class Coach implements Serializable
{
@Column(name = "license_nbr")
private String licenseNbr = null;
@Id
@OneToOne
@JoinColumn(name = "id")
private Person person = null;
...
}
Player 和 Coach 实体类几乎相同。
这里的问题是两个双向关联(mappedBy)。这些映射与 EclipseLink 完美配合,但 Hibernate 莫名其妙地因 AnnotationException 异常:
Exception in thread "main" javax.persistence.PersistenceException: [PersistenceUnit: persons] Unable to configure EntityManagerFactory
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:374)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:56)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:48)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:32)
at tld.persons.Main.main(Main.java:32)
Caused by: org.hibernate.AnnotationException: Unknown mappedBy in: tld.persons.model.Person.coach, referenced property unknown: tld.persons.model.Coach.person
at org.hibernate.cfg.OneToOneSecondPass.doSecondPass(OneToOneSecondPass.java:159)
at org.hibernate.cfg.Configuration.originalSecondPassCompile(Configuration.java:1686)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1393)
at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1345)
at org.hibernate.ejb.Ejb3Configuration.buildMappings(Ejb3Configuration.java:1477)
at org.hibernate.ejb.EventListenerConfigurator.configure(EventListenerConfigurator.java:193)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:1096)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:278)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:362)
... 4 more
当切换到老式 JPA 1.0 映射时,一切都运行良好。Hibernate 似乎对上述映射有问题。
我查看了许多其他问题报告,实际上 hibernate.org 上的论坛充满了类似的未解决问题,但我找不到任何线索说明为什么会引发异常。
对我来说,这似乎是一个休眠错误。有人可以证实这一点吗?(注意我使用的是 Hibernate 3.6)