Issue
We have a legacy table and we don't want to add a discriminator column into it. Is it possible to have table-per-hierarchy without a discriminator column?
My parent class code:
@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
}
My 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
}
You can see in my above example, I have to use a discriminator.
Solution
SINGLE_TABLE
is a very powerful strategy but sometimes, and especially for legacy systems, you cannot add an additional discriminator column. For that purpose Hibernate has introduced the notion of discriminator formula: @DiscriminatorFormula
is a replacement of @DiscriminatorColumn
and uses an SQL fragment as a formula for discriminator resolution (no need to have a dedicated column).
@Entity
@DiscriminatorFormula("case when forest_type is null then 0 else forest_type end")
public class Forest { ... }
Answered By - Aslam anwer
Answer Checked By - Senaida (JavaFixing Volunteer)