Reputation: 445
I have two classes C1 and C2. Each persists to its own table. Each has its own Hibernate XML description, mentioning its own table. There is no connection between these classes at all.
Except that C1 is a subclass of C2.
Obviously C1's XML copies a lot from C2's (with some stuff added), but it's a separate copy. Again: neither XML file mentions the other class or the other table.
But now, when I do a "From C2" query, Hibernate pulls in all of both tables.
Logically, this makes sense: a C1 is in fact a C2, so if I want all C2s I need the C1s as well, so we need to read all of C1's table. Hibernate must be using reflection to detect subclass C1 of C2.
Supposing this is expected behavior (though it wasn't expected by me!) how do I avoid it? Is there any way I can tell Hibernate that when I say "From C2" I really mean just C2 and not C1 to boot? Is there a clause I can add to the query that will restrict it to objects not of type C1, also avoiding the performance hit of querying C1's table in the first place?
Upvotes: 1
Views: 1079
Reputation: 5407
When you select from C2 it will also select C1 by default in hibernate. It's called Polymorphic queries. see Polymorphic queries , and Tutorial.
To fix/solve it you should add Polymorphism annotation with type PolymorphismType.EXPLICIT
@Polymorphism(type = PolymorphismType.EXPLICIT)
from https://docs.jboss.org/hibernate/orm/5.2/javadocs/
IMPLICIT -This entity is retrieved if any of its super entity are retrieved. The default,
EXPLICIT -This entity is retrieved only if explicitly asked.
Upvotes: 2