我正在使用Spring Boot开发一个简单的Web应用程序。我将继承层次结构中的多个实体映射到一个预先存在的表。这是我的基类:
@Entity
@Table(name = "kpodr")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorFormula("CASE WHEN k_se = 3 THEN 'FACULTY' WHEN k_se = 4 THEN 'DEPARTMENT' ELSE 'COMMON' END")
@DiscriminatorValue("COMMON")
public class Unit {
@Id
@Column(name = "k_podr")
protected long id;
...
}
和子类:
@Entity
@DiscriminatorValue("FACULTY")
public class Faculty extends Unit {
...
}
@Entity
@DiscriminatorValue("DEPARTMENT")
public class Department extends Unit {
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "k_pvu")
private Faculty faculty;
...
}
一切正常,我可以获取所需的任何数据,甚至包括拥有
Faculty
的Department
。但是现在我需要使用基本的Unit
类型来映射其他实体:@Entity
@Table(name = "mesto_rab")
public class Workplace {
@Id
@Column(name = "id")
private long id;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "k_podr")
private Unit unit;
...
}
当我尝试获取工作场所时,我得到
org.hibernate.WrongClassException: Object [id=85] was not of the specified subclass [workload.faculty.Faculty] : loaded object was of wrong class class workload.unit.Unit
。我在代码中找到导致此异常的确切位置。如果删除
Department
和Faculty
之间的关联,那么一切都会按预期进行。@Entity
@DiscriminatorValue("DEPARTMENT")
public class Department extends Unit {
@ManyToOne(fetch = FetchType.EAGER) <====|
@JoinColumn(name = "k_pvu") <====| Remove this
private Faculty faculty; <====|
...
}
如何修复
org.hibernate.WrongClassException
并保持部门之间的联系? 最佳答案
似乎带有id=85
的行已由Department
引用,但是其区分符公式的计算结果并非"FACULTY"
。
换句话说,您可能有一行kpodr(id = 85, k_se <> 3)
和另一行kpodr(k_se = 4, k_pvu = 85)
,这就是导致此问题的原因。