True Confessions of a Hibernate User
by Bill Siggelkow
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.
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:
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!
This sounds like exactly like a mapping issue. If you've checked and you don't see the problem get another pair of eyes to take a look. If that fails, don't spend too much time guessing--Hibernate's open source--just pull out your handy-dandy debugger.
re: what if...
I strongly encourage you to look at Xdoclet to solve future mapping issues. It puts the mapping metadata inside your Java classes using specially-formatted Javadoc, and you'll never have a mapping issue (related to the incorrect type) again.
You may also integrate the generation of the mapping files using Ant tasks.
After spending an entire evening trying to figure out why my commit() wouldn't work, I finally tracked the problem down to a StringType ClassCastException.