HGPB
HGPB

Reputation: 4376

Hibernate Criteria.list() causing java.lang.ClassCastException

I'm coming back to Java after a few years away and this is my 2nd day looking at hibernate and don't fully understand it yet.

I have the following criteria which is performing a join:

Criteria cr = s.createCriteria(Bla.class, "bla");
cr.setFetchMode("bla.nodePair", FetchMode.JOIN);
cr.createAlias("bla.nodePair", "node_pair");
cr.add(Restrictions.in("bla.blaName", (List<Bla>) getBlas()));

ProjectionList columns = Projections.projectionList()
    .add(Projections.property("node_pair.priNode"))
    .add(Projections.property("bla.blaName"))
    .add(Projections.property("node_pair.secNode"))
    .add(Projections.property("bla.port"));

cr.setProjection(columns);
List<Object[]> list = cr.list(); // Exception occurs here

This is creating as far as I can tell a valid SQL query and exactly what i'm after.

However, when I try to generate a list of results cr.list(); I get:

java.lang.ClassCastException: com.some.package.domainobject.Bla cannot be cast to java.lang.String

How should I construct my List. Any pointers much appreciated.

Upvotes: 1

Views: 2184

Answers (1)

cghislai
cghislai

Reputation: 1801

In Criteria API, the Exception is always(?) thrown when attempting to get the results.

In your case, the problematic line is probably

cr.add(Restrictions.in("bla.blaName", (List<Bla>) getBlas()));

You seem to check if a java.lang.String is part of a Collection<Bla>.

If your equals and hashcode methods in Bla use the blaName field, you should be able to use

cr.add(Restrictions.in("bla", (List<Bla>) getBlas()));

Otherwise, implements a getBlasNames() function which returns a List<String>

Upvotes: 2

Related Questions