How to omit joining of superclass in JPA when Im querying subclass only?


#1

Hi,

I have a JPA model with class hierarchy:

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class A {
    @Id
    @GeneratedValue
    private Long id;

    private String parentVal;

    // getters setters here
}

@Entity
public class SubA extends A {
    private String val;

    // getters setters here
}

It is a simplification of my real model. I have a JPQL query

select val from SubA

which generates this sql

select suba0_.val as col_0_0_ from SubA suba0_ inner join A suba0_1_ on suba0_.id=suba0_1_.id

There is a inner join to the superclass table, which is useless. I need nothing from there. But it looks like it is impossible to get rid of it. I asked that on stackoverflow already and also debug Hibernate code.

I start thinking about creating of hibernate patch which allows that. First option would be to detect if I need to join parent table, another option would be explicitly say “do not join it”. What do you think, how is it difficult? Could you direct me? Thank you.


#2

If you can send a Pull Request, that would be great.


#3

Could somebody who knows hibernate core internals better help me with the Pull Request? I mean kind of high level help, just direct me what will be the best way to do it.


#4

Just debug Hibernate Core to get familiar with the code base. It’s just code after all.


#5

Ok, I plan in my patch extend HQL syntax by “WITHOUT ANCESTOR”. Examples:

SELECT val FROM SubA WITHOUT ANCESTOR;
SELECT val FROM b JOIN WITHOUT ANCESTOR b.prop;
SELECT val FROM b JOIN WITHOUT ANCESTOR SubA ON (b.id = SubA.id);

Could be this solution merged into Hibernate?


#6

The HQL parser is completely rewritten in 6.0 so its not worth adding it for 5.x. For the moment, you could simply use a native SQL as a workaround.

Now, back to your proposal, I suppose we should not provide the WITHOUT ANCESTOR keyword as Hibernate could detect that the property belong to the subclass only, so this should be automatically resolved.