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?
I’m new in JPA. I have a superclass called Person and two subclasses Teacher
Share
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
And that leaves you to a beautiful change:
With the following classes
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.