Overlap in an inheritance

hello i am using spring boot, spring data jpa and postgres. I have the following scenario: I have 3 classes that make up a hierarchy person, student, and teacher, where student and teacher inherit from person.

@Entity
@Table(name = "person")
@Inheritance(strategy = InheritanceType.JOINED)
public class Person {

    // Personal Data
    @Id
    @GeneratedValue(generator = "ID_GENERATOR_POOLED")
    protected Long id;

    @Column(length = 11, unique = true, nullable = false)
    protected String idNumber;
}
@Entity
public class Student extends Person {}
@Entity
public class Teacher extends Person {}

the inheritance strategy is joined. It is possible for a student to be a teacher. The problem is when inserting a teacher who is already a student or vice versa. Hibernate tries to save and it does so by inserting a new tuple in the person relation, generating repeated data and even an error because the idNumber is unique. How can i fix this? that is to say that if the person already exists, then only insert in the relationship student or teacher as the case may be

You can fix this by not modelling this through inheritance. You can’t model this this with inheritance as that would require an object to be an instance of both, Student and Teacher, which is impossible in Java.

I would suggest to model this through composition, i.e. remove the inheritance, and let Student and Teacher refer to a Person through a @OneToOne mapping.

1 Like