Search code examples
javahibernatejpasingle-table-inheritance

Java SingleTable inheritance in db structure using JPA/Hibernate


I have models/Entities as follow:

@Entity
@DiscriminatorColumn(name="type")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
public class Insurance extends Generic<Insurance> {
    @OneToOne public myInsurance.models.liability.hivAndVHProtection.Hiv_Answer hivAndVHProtectionAnswer;
}


@MappedSuperclass
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class Answer extends Generic<Answer> {}

@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorValue("A")
public class Hiv_Answer extends Answer {
    @OneToOne public HivAndVHProtection_Variant variant;
}

@Entity
@Inheritance
@DiscriminatorValue("E")
public class Hiv_AnswerForEntities extends Hiv_Answer {
    public int proffesionGroup;
    public int personCount;
    public int contributionPerPerson;
    @Transient public int totalContribution;
}

I would like to have in db two tables: Insurance and Hiv_Answer

I would like that Entities: Hiv_Answer and Hiv_AnswerForEntities be persisted in table Hiv_Answer (share common ID pool)

I would like to have in table Insurance relation to table Hiv_Answer f.e. in column Hiv_Answer_id

I've tried a lot of combination with annotation. None worked like it supose.

Current configuration for me seems to be OK, but it isn't. I am getting extra table: Hiv_AnswerForEntities, and I don't have relation to Hiv_Answer table at all.

It seems that instead use strategy=InheritanceType.SINGLE_TABLE from Hiv_Answer Entity it use strategy=InheritanceType.TABLE_PER_CLASS from superclass Answer

I can't find my mistake.

Please help me solve this.


Solution

  • In JPA you can't redefine your inheritance strategy down the inheritance tree, the root definition of the inheritance sets it for the whole inheritance tree