Fun With Hibernate Inheritance

(Recovered from my old Blog).

I had a relatively simple requirement, with a relatively simple solution – but it is worth recording for simple reference.

Suppose I have two Hibernate classes Cat and Dog, both of which derive from the abstract class Animal. Suppose further that both Cats and Dogs can have a child collection of the class Toy.

Since Set<Toy> is shared, we want to do all the hard work in the Animal class, rather than repeat it twice.

Finally, assume that for convenience sake – the underlying table structure is shared, with just a column to indicate whether the entry is a CAT or a DOG.

All very simple so far.

If we want to annotate this class to fulfill the requirements above, we have to:

Declare Cat and Dog as @Entity, since these become the instantiated classes.
Important – Animal also needs to be an @Entity to allow for the @ManyToOne mapping in Toy. (Remember – we said we wanted the ToySet to be shared. If you don’t declare Animal as an @Entity we will get ‘unknown entity’ exceptions.
State that Animal is the top of tree with @Inheritance.
Tell Hibernate which column should be used to discriminate between classes when mapping with @DiscriminatorColumn.
So our classes become:

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: