Goulash
Goulash

Reputation: 3848

Hibernate Query parent based on different subtype properties

I want to write a HQL query which selects all of the Parent entities, based on two different properties which exist on child entities.

abstract class Parent {
  int id;
  String type;
}

class ChildOne extends Parent {
  Colour colour;
}

class ChildTwo extends Parent {
  Size size;
}

My working query looks like this: SELECT p FROM Parent p LEFT JOIN p.colour c LEFT JOIN p.size s WHERE c.shade = 'RED' OR s.width = 15.

This query does work fine, but of course it gives me warnings about colour and size not existing on Parent in my join statements. How can I fix it so that I do not get these warnings?

The warning messages that I get is: Can't resolve symbol 'colour' and Can't resolve symbol 'size'.

Upvotes: 1

Views: 635

Answers (3)

Goulash
Goulash

Reputation: 3848

I was able to resolve the issue and get rid of the warnings by using the following query:

SELECT p FROM Parent p
LEFT JOIN ChildOne c1 on p = c1
LEFT JOIN ChildTwo c2 on p = c2
WHERE c1.shade = 'RED' OR c2.width = 15

Upvotes: 0

Christian Beikov
Christian Beikov

Reputation: 16462

I guess you are seeing IntelliJ or Eclipse warnings? You can't get rid of them. Also, this is a HQL or Hibernate specific feature. In plain JPQL you have to use the TREAT operator to access subtype properties, but no JPA implementation gets this right i.e. they introduce type constraint predicates that are semantically wrong. Hibernate 6.0 will fix this, but for now, I would recommend you use the query you already have and ignore the warnings.

Upvotes: 1

ShittyCode
ShittyCode

Reputation: 1

Try to use @Inheritance(strategy = InheritanceType.JOINED) on Parent class

Upvotes: 0

Related Questions