Friday, November 5, 2010

Hibernate ClassCastException

Issue:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.altair.cls.entity.Response
    at com.altair.cls.dao.impl.HibernateResponseDAO.getResponseByQuestionAndGradedItem(HibernateResponseDAO.java:30)

HibernateResponseDAO.java:




Solution: (Courtesy of Scott Basinger)

Change 

"from Response r left join r.question q left join r.gradedItem i "   to

"select r from Response r left join r.question q left join r.gradedItem i "

I will see if I can get him to post a reply which would explain why the change fixed it.
What I got from him was that since it is a join of two classes(tables), Hibernate creates a general "java.lang.Object", unless you specifically tell it to create a "Response" with "select r from Response r".
I have to get better with Hibernate and databases in general....uhhh

1 comment:

  1. Correct. Since the HQL is creating a composite object to hold a Response, Question and GradedItem a generic Object is returned. By stating explicitly that you are only concerned with the Response a typed class can be returned.

    ReplyDelete