I’ve been writing a small application to help me design sequences for an animated scene on my MRR. I have the basic application working and now I’ve been adding the ability to save/load data. Rather than using a file, I’m using a database and Hibernate. Now, I’ve used Hibernate in the past but not in any level of detail.

In the spirit of growing as developer (which I don’t do professionally anymore) I decided to exploit the magic of Hibernate and let it manage the full lifecycle of all my objects – automagically. In the process, I’ve become super frustrated at the simplest things that should just “work”. I’ve recently made a breakthrough and feel compelled to share it with everyone should someone make the same mistake I’ve made.

Long story short: I was using an int as the primary key to avoid instantiating a new Integer object for each instance of my object. Well, it seems Hibernate couldn’t figure out that my objects were new and unmanaged when I was using an int, but by converging to an Integer for the primary key, everything magically started working. I recall a property to tell Hibernate what the unsaved ID value was, but I didn’t try it as the error it was returning was hardly intuitive relative to the fix.

I was receiving the following error:

ERROR AbstractFlushingEventListener - Could not synchronize database state with session
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

All my Googling (8 tabs open right now) pointed to a transaction issue, not a primary key issue. Moreover, because the application worked fine with 2 objects, but not three, I really felt it was a state problem with the integrity of the objects, not the primary key. So, if you are getting the state error and your not modifying objects out side the transaction, it’s likely Hibernate can’t figure out if your objects are new or old, so it’s going an update for you instead of an insert. The update will fail because the object doesn’t exist. As an aside, -1 one looks like a valid primary key to the computer 😉

So, lesson learned: Google can answer every question you have – if you ask the right question. This is my attempt to let others ask the “obvious” question and get the non-obvious answer. Peace.