If you are using Hibernate for your persistence layer, debugging can be a challenge. I recently had a problem that was driving me nuts …


In short, I was stepping through code in my IDE’s debugger. I had traced the problem to a query that I was executing with Hibernate. An exception was thrown when I attempted the query … here’s the stacktrace.

java.lang.ClassCastException
net.sf.hibernate.type.LongType.set(LongType.java:28)
net.sf.hibernate.type.NullableType.nullSafeSet(NullableType.java:48)
net.sf.hibernate.type.NullableType.nullSafeSet(NullableType.java:35)
net.sf.hibernate.persister.EntityPersister.dehydrate(EntityPersister.java:403)
net.sf.hibernate.persister.EntityPersister.insert(EntityPersister.java:521)
net.sf.hibernate.persister.EntityPersister.insert(EntityPersister.java:498)
net.sf.hibernate.impl.ScheduledInsertion.execute(ScheduledInsertion.java:28)
net.sf.hibernate.impl.SessionImpl.executeAll(SessionImpl.java:2362)
net.sf.hibernate.impl.SessionImpl.execute(SessionImpl.java:2316)
net.sf.hibernate.impl.SessionImpl.autoFlushIfRequired(SessionImpl.java:1813)
net.sf.hibernate.impl.SessionImpl.getQueries(SessionImpl.java:1507)
net.sf.hibernate.impl.SessionImpl.find(SessionImpl.java:1472)
net.sf.hibernate.impl.QueryImpl.list(QueryImpl.java:45)

My first reaction was to analyze what was wrong with the query. I checked and found nothing wrong. The ClassCastException indicated that I had some incompatability in a Hibernate mapping file … this deduction was accurate.

The problem, however, was not with the object that I was performing the query. The problem was related to the mapping of a different object that I had inserted into the database earlier in the the life of this particular transaction. Two things clued me in — first, on inspection, the stack trace indicates that the error was on EntityPersister.insert(). Second, I turned “show SQL” on with the following Hibernate configuration setting:

        <property name="hibernate.show_sql">true</property>

Looking at the logs out of Tomcat clearly showed that the error occured when executing an SQL insert statement.

What was happening was that Hibernate had not flushed the insert to the database. It was not until I issued a query that Hibernate attempted to execute the insert statement. Once I realized that the offending object was not the one being queried but the one being inserted, I quickly located the problem in my mapping XML file. I had incorrectly defined the type of a property as a Long instead of a String. A quick change to the XML file and the problem was solved.

A few lessons I learned here:

  • Turn on Show SQL when debugging with Hibernate
  • Trust the log file
  • Don’t just scan the stack trace, read it carefully

In hindsight the problem is, of course, obvious — in the words of the great poet Homer — Doh!