PDA

View Full Version : hibernate template save and saveorupdate problems



Edward Kenworthy
Sep 15th, 2004, 01:37 PM
Hi

I've gotten my spring application to work. Well mostly. I tried adding a new entity to the database (Hibernate) using getHibernateTemplate().saveOrUpdate(splash); but if I use that then it throws a SQL Exception that it can't find the row (well duh!).

So I changed it to getHibernateTemplate().save(splash); but now I get an exception that I'm trying to set a not null column to null which as far as I can tell is the id column which in the Hibernate mapping I set to:

<id name="id" type="int" column="id">
<generator class="native"/>
</id>

So shouldn't it automagically auto-generate it?

What am I doing wrong?

irbouho
Sep 15th, 2004, 01:55 PM
You must help Hibernate decide if your entity is a new one (so it create it) or an existing one that is being updated. Hibernate uses "unsaved-value" for this reason:

<id name="id" type="int" column="id" unsaved-value="0">
<generator class="native"/>
</id>

With this mapping you can use saveOrUpdate, and Hibernate will resolve the correct operation to execute depending on the value of the id column.

HTH

Edward Kenworthy
Sep 16th, 2004, 02:31 AM
Hi

Thanks that makes saveorupdate work but doesn't solve the second problem (saveorupdate still fails, just for a different reason now) I understood that hibernate should auto-generate the id yet it seems to be trying to insert a null value for the id into the database, which unsurprisingly is barfing at trying to insert a null into a non-null column.

I've done similar things with hibernate before and they worked: is there something in spring that changes the rules?

Edward

Edward Kenworthy
Sep 17th, 2004, 02:25 AM
I've found the problem: what it comes down to I was blindly following some (poor) examples from the O'Reilly Hibernate Developers notebook which didn't actually setup the primary key properly (the code manually generated a primary key value when it inserted a new row!)