views:

275

answers:

1

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)
+2  A: 

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
Pascal Thivent
Thanks, I fixed the example. The original code used '?' for prepared statement.
Petteri Hietavirta
@Petteri I just tested this HQL query and it works as expected (without quotes or double quotes). It's not a `String` that is expected, not sure you can use a prepared statement here (at least not with `setString`)
Pascal Thivent
Yep, works here as well now. Thanks a lot!
Petteri Hietavirta