Search code examples
javahibernatejpahql

How to cast a referenced entity in HQL to its sub-class


Suppose there are following entities (JPA annotations are not written):

class Questionnaire {
    ...
}

class Policy {
    private Questionnaire questionnaire;
    ...
}

class LifeQuestionnaire extends Questionnaire {
    private String someField;
}

class LifePolicy extends Policy {  
    ...
}

Well as it seems a Policy references a Questionnaire, but a LifePolicy references a LifeQuestionnaire (this restriction is always true).

Is there any way I can write a query like this:

from LifePolicy lplc
where ((LifeQuestionnaire) lplc.questionnaire).someField = :fieldValue

As you can see, I want to have some kind of casting in the HQL query, because someField is only available in LifeQuestionnaire.


Solution

  • I had exactly the same problem and have found a solution that worked for me. Its not very nice but it works. Try using a 'Cross' join. e.g.

    select (specify what you want to fetch) 
    from LifePolicy as lp, LifeQuestionnaire as lqn 
    inner join lqn.questionnaire as q 
    where lqn.id = lp.id 
    and q.someField = :fielfValue
    

    sources:

    https://www.jumpingbean.co.za/blogs/mark/hibernate https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html#queryhql-from