Search code examples
javainheritancejpaumloverlapping

JPA UML inheritance overlapping


I'm new in JPA. I have a superclass called Person and two subclasses Teacher and Student. Most of time a Person is just a Teacher or a Student, but sometimes one Person is both Student and Teacher and I need to persist it. Does anybody know how can I map this UML inheritance overlapping in JPA? Is it possible?


Solution

  • I think you should think it in another way, instead of using the "is A" that would let you think on inheritance, you could think it as a person having more than one role, so if you think it this way, you could solve it with aggregation, like the following

    public class Person {
        private TeacherProfile teacherProfile;
        private StudentProfile studentProfile;
    }
    

    And that leaves you to a beautiful change:

    public class Person {
        private Set<Profile> profiles;
    }
    

    With the following classes

    public abstract class Profile {
        private String name;
        //common data
    }
    
    public class TeacherProfile extends Profile {
        //teacher data
    }
    
    public class StudentProfile extends Profile {
        //student data
    }
    

    And that can solve your problem elegantly without breaking your inheritance idea.

    I can explain why your original idea, even though is possible on a relational database, it is not possible under the objects world, consider getting the Person by ID, if you had the same person with the two "roles" then what instance would hibernate return? a Student would be wrong and a Teacher would be wrong. This would be possible though if java were a multiple inheritance language, which has its own problems :)

    Hope I made it clear to you.