Announcement Announcement Module
Collapse
No announcement yet.
hibernate template save and saveorupdate problems Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • hibernate template save and saveorupdate problems

    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?

  • #2
    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:
    Code:
    <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

    Comment


    • #3
      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

      Comment


      • #4
        Problem solved.

        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!)

        Comment

        Working...
        X