Friday, March 13, 2009

The case of the WrongClassException

Yesterday, one client reported a strange bug in his application. It was an org.hibernate.WrongClassException during loading of some pojos from the database. I should mention here that the application is EJB3-JPA based with SmartGWT for the front-end. The exception was thrown when trying to load a specific object of class A and hibernate reported that the object was already loaded in the session but it was of the wrong class (class B). After playing around the database and the pojos annotations I saw that the two classes were subclasses of a common class and that the @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) annotation has been used on the parent, meaning that the two subclasses were mapped onto separate tables. I luckily remembered that in that case the primary keys have to be unique among the two tables even though we are talking about separate tables, otherwise hibernate will get confused when an object from table A is already loaded and it tries to load an object from table B with the same id. It thinks that the object is already loaded but it is of the wrong class. The odd thing in my case was that the two tables actually had different keys!!! What had happened as I discovered later was that the client had added some lines in one of the tables without caring about the key uniqueness between the two tables, thus leading to the WrongClassException problem.

Conclusion: Never allow the client touching the database!!!

1 comment:

Anonymous said...

Thanks for the post, this took care of an issue I just started seeing today.