Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA/Hibernate query with class name?

In this example com.test.Cat extends com.test.Animal and there is no field DB in CAT table of com.test.Cat explicitly defining its type (it wasn't me).

When I query my animals from DB I get a collection of Animals.

It is possible to sort them by class name:

order by r.class

but is there a way to use class name as a criteria? For example I would like to get all animals expect dogs. But no luck - even this does not work:

where r.class = ?      (String "ccc.test.Cat")

as I get an exception:

Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
    at org.hibernate.type.IntegerType.set(IntegerType.java:64)
    at org.hibernate.type.NullableType.nullSafeSet(NullableType.java:154)
    at org.hibernate.type.NullableType.nullSafeSet(NullableType.java:136)
    at org.hibernate.param.PositionalParameterSpecification.bind(PositionalParameterSpecification.java:62)
    at org.hibernate.loader.hql.QueryLoader.bindParameterValues(QueryLoader.java:514)
    at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1589)
    at org.hibernate.loader.Loader.doQuery(Loader.java:696)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259)
    at org.hibernate.loader.Loader.doList(Loader.java:2228)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2125)
    at org.hibernate.loader.Loader.list(Loader.java:2120)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:401)
    at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:361)
    at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:196)
    at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1148)
    at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102)
    at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:67)
like image 906
Petteri H Avatar asked Feb 23 '10 11:02

Petteri H


1 Answers

According to the chapter 14.9 of the documentation, you shouldn't use double quotes:

The special property class accesses the discriminator value of an instance in the case of polymorphic persistence. A Java class name embedded in the where clause will be translated to its discriminator value.

from Cat cat where cat.class = DomesticCat
like image 111
Pascal Thivent Avatar answered Sep 18 '22 17:09

Pascal Thivent