我们有一个旧表,我们不想在其中添加鉴别器列。 是否可以在没有鉴别器列的情况下按层次结构表?
我的父类代码:
@Entity
@Table(name = "SHAPE1")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "Discriminator",
discriminatorType = DiscriminatorType.STRING)
@DiscriminatorValue(value = "S")
public class Shape {
@Id
@Column(name = "Shape_Id")
int shapeId;
@Column(name = "Shape_Name")
String shapeName;
public Shape() {
}
public Shape(int id, String shapeName) {
this.shapeId = id;
this.shapeName = shapeName;
}
// getters and setters
}
我的 child 类(class):
@Entity
@DiscriminatorValue(value = "R")
public class Rectangle extends Shape {
@Column(name = "Rectangle_Length")
int length;
@Column(name = "Rectangle_Breadth")
int breadth;
public Rectangle() {
}
public Rectangle(int id, String shapeName, int length, int breadth) {
super(id, shapeName);
this.length = length;
this.breadth = breadth;
}
// getters and setters
}
您可以在上面的示例中看到,我必须使用鉴别器。
最佳答案
SINGLE_TABLE
是一个非常强大的策略,但有时,特别是对于遗留系统,您无法添加额外的鉴别器列。为此,Hibernate 引入了判别器公式的概念:@DiscriminatorFormula
是 @DiscriminatorColumn
的替代品,并使用 SQL 片段作为判别器解析的公式(无需拥有专门的专栏)。
@Entity
@DiscriminatorFormula("case when forest_type is null then 0 else forest_type end")
public class Forest { ... }
关于java - Hibernate 中没有鉴别器列的按层次结构表策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22397552/