I have a relatively large class hierarchy in terms of width, so many classes inheriting from one root class. The maximum depth of the hierarchy is only 4 levels when counting from the root to the leaves of the hierarchy tree. Let’s call the root class
RootClass and the leaves
L1, L2, ..., L20). I only store objects of type
Lx in the database, never of
RootClass or an intermediate type.
Lxes are referred to by various other classes but only stored as
RootClasses there. The ORM is as follows:
RootClass has a table annotated with a single table inheritance strategy. As storing all
Lx's varying properties in this
RootClass table is extremely inefficient, I have secondary tables for each
Lx that contains additional properties and theoretically I can determine the actual type of an object - and hence table - by the discriminator value in the
RootClass's table. My reasoning is here that Hibernate should be able to efficiently query a stored object, as it can infer which two tables to join from the discriminator value.
The problem: The
RootClass contains a many-to-many relation to (a Set of) other
RootClass objects. When I try to fetch that set to iterate over its content hibernate produces a query with over 80 joins. This causes a
java.sql.SQLException: Too many tables.
I assume hibernate is trying to fetch the data I require with a single statement and the only way to do this is such a massive join. Is there a way to get hibernate to fetch the data more intelligently by using the discriminator values and several queries? Is my ORM bad and a way to fix this issue by improving the ORM? I have tried a lot of mappings for this class hierarchy and haven’t come up with anything better so far.
Thanks for any tips!