Skip to content

Inheritance

Michele Scuttari edited this page Nov 14, 2019 · 4 revisions

When an entity class is extended, a table for each parent and child entity class is created, each one table holding only the columns specific to its entity class. A small exception is for the primary keys, which are inherited by the children tables in order to join them to the parent ones at query time.

Every parent entity must specify a discriminator column, which is internally used to identify the child type of each parent tuple. The specified column is not required to exist already and can also be a join column that indeed refers to another entity.

@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING)
public abstract class Parent {
    @Id
    @Column(name = "id")
    public long id;

    @Column(name = "type")
    private String type; // private visibility just to avoid externally set values that may be invalid
}

// The Parent table will have the "id" and "type" columns.

Every child entity must specify its discriminator value, in order to specify which value should be stored in the discriminator column of the parent entity.

@DiscriminatorValue(value = "one")
public class ChildOne extends Parent {
    @Column(name = "test1")
    public String col;
}

@DiscriminatorValue(value = "two")
public class ChildTwo extends Parent {
    @Column(name = "test2")
    public int col;
}

// The ChildOne table will have the "id" and "test1" columns. The "id" column is inherited by Parent.
// The ChildTwo table will have the "id" and "test2" columns. The "id" column is inherited by Parent.
Clone this wiki locally