What and when is the best scenario to use DiscriminatorValue annotation in hibernate?
Let me explain to you with an example . Suppose you have an class called Animal and under Animal class there are many subclasses like Reptile, Bird ...etc.
And in the database you have table called ANIMAL
---------------------------
ID||NAME ||TYPE ||
---------------------------
1 ||Crocodile ||REPTILE ||
---------------------------
2 ||Dinosaur ||REPTILE ||
---------------------------
3 ||Lizard ||REPTILE ||
---------------------------
4 ||Owl ||BIRD ||
---------------------------
5 ||parrot ||BIRD ||
---------------------------
Here the column TYPE is called DiscriminatorColumn , because this column contains data that clearly separates Reptiles and Birds. And the data REPTILE and BIRD in column TYPE are the DiscriminatorValue.
So in the java part this structure would look like :
Animal class:
@Getter
@Setter
@Table(name = "ANIMAL")
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(discriminatorType = DiscriminatorType.STRING, name = "TYPE")
public class Animal {
@Id
@Column(name = "ID")
private String id;
@Column(name = "NAME")
private String name;
}
Reptile class :
@Entity
@DiscriminatorValue("REPTILE")
public class Reptile extends Animal {
}
Bird class :
@Entity
@DiscriminatorValue("BIRD")
public class Bird extends Animal {
}