从MappedSuperclass继承关系



我创建了一个名为";CommonClass;其中包含大量其他类的一些公共属性。此外,我需要该类指定公共关系,例如与另一个名为"的类;关系类";。

我这样做:

/* ##### CommonClass ##### */
@MappedSuperclass
public class CommonClass {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
...
@ManyToOne
@JoinColumn(name = "fk_relation_class")
private RelationClass relationClass;
// === Class getters & setters ===============================
... 
}
/* ##### CommonClass ##### */

/* ##### ChildClass ##### */
@Entity
public class ChildClass extends CommonClass{
private String specificAttribute;
...
// === Class getters & setters ===============================
...
}
/* ##### ChildClass ##### */

/* ##### RelationClass ##### */
@Entity
public class RelationClass {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
...
@OneToMany(mappedBy = "relationClass")
private List<CommonClass> commonList = new ArrayList<CommonClass>();
// === Class getters & setters ===============================
...
}
/* ##### RelationClass ##### */

问题是没有将CommonClass识别为一个实体,这是正确的,但它是一个MappedSuperClass,所以从逻辑上讲,它应该让子类继承关系。

这是我得到的错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: com.xxx.dao.entities.RelationClass.objectList[com.xxx.dao.entities.CommonClass]
...
Caused by: org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: com.xxx.dao.entities.RelationClass.objectList[com.xxx.dao.entities.CommonClass]

所以这似乎是不可能的。如以下链接所述:"映射超类的主要缺点是它们不能被查询或持久化您也不能与映射的超类有关系">

https://en.wikibooks.org/wiki/Java_Persistence/Inheritance

,但它是一个MappedSuperClass,因此从逻辑上讲,它应该让子类继承关系。

我认为原因是Hibernate(或任何JPA实现(在启动阶段不能确定将添加到@OneToMany列表中的类是否是实体。甚至可以添加一个从CommonClass扩展但不是@Entity的Java类。

最新更新