Femgineer

Class Cast Exception is a Proxy Problem

I often face the following exception in Hibernate not on my local developer machine, but in production across several servers:

java.lang.ClassCastException: mint.hibernate.MathCourse$$EnhancerByCGLIB$$ed898f0d

This happens when I try to do something like this:

Set<Courses> courses = getCoursesDao().getCourses(userId);

for (Course c : courses) {
MathCourse mc = (MathCourse) course;
// do something with mc
}

Assume MathCourse is a subclass of the abstract parent class Course. The gist of the problem is that Hibernate is trying to optimize and avoid going to the database by returning a proxy object. However, a proxy object cannot be downcast to the subclass object, the exception occurs because of downcasting. The solution to the exception is to return the real instance of the object.

One solution is to return the real instance of the object. To do this you could add a method to the DAO to return a generic. Create the function in the DAO class. Then during runtime the generic will be resolved to the appropriate subclass.

public class CourseDao {
public <T extends Course> getGenericCourse() {
Session session = getCurrentSession();
Course course = (Course) session.get(Course.class, courseId);
if (course != null) {
// type is an enum
switch (course.type()) {
case MATH:
course = (MathCourse) session.get(MathCourse.class, courseId);
break;

}
  …
return (T) course;
}

Exit mobile version