Modelling question: combine collection and inheritance

I have a modelling question: I’m looking for some kind @ManyToAny but where each of the Many always has the same kind of Any. I’ll clarify…

So I’m still working on the model I described in this topic. The relevant part is the relation between Tasks and (abstract) SubTasks, where a concrete SubTask can be an instance of any of a number of subclasses of SubTask. There are many of those subclasses, so I want to avoid single table inheritance. Each Task has a number of SubTasks, but these SubTasks are all of the same subclass per Task. That means there’s no strict need for a link table in the database: I can keep a discriminator column in the Tasks table, and for each of the SubTask tables there’s a foreign key to its Task.

The queries to fetch a Task’s SubTasks are easy enough, but they would preferably only select from the right SubTask table, determined at runtime. Is there perhaps an elegant way to express this kind of relation, hopefully without delving to deep into Hibernate internals? :thinking: The best solution I can think of right now is to manually fetch the SubTasks with criteria queries or something, where the target table is dynamically chosen. In my Java code, a Task has a fixed set of SubTasks so I guess that could do. But then I may be missing out on the expressive power and performance optimization that Hibernate has to offer, so any expert tips would be highly appreciated.

but they would preferably only select from the right SubTask table, determined at runtime

To do that, Hibernate would need to know the Task type for a one-to-many association. I think that maybe a query like select t from Task t join fetch treat(t.subTasks as Type1SubTask) should be able to do the trick, but I have no idea how your mapping looks like.

Maybe share the model here again so that we can talk about the same thing. Also, how does the query look like that you want to execute?

Hi. Thanks for the quick reply again.

The model/mapping is still in flux, I have to get it to work op the PHP side. When I have it working I’ll post the mapping and table structure, that will be easier indeed. The query you mention looks promising, but I’ll need to take a much closer look at HQL to judge that. :smiley:

So more details following soon but you may have already solved my question…