views:

1267

answers:

1

So, I just stood up a Spring Hibernate app and I can't seem to get my mapping file right. I am using MySql 5 and an auto incrementing key. Here is the ID portion of my mapping file.

<hibernate-mapping>
     <class name="org.XXXXXXX.Contact" table="contact">
        <id name="id" column="id" type="int" unsaved-value="null">
            <generator class="native" />
        </id>

Here is the SQL generated

insert into contact (title, first_name, middle_name, last_name, suffix, job_title, dob, passport_number, passport_expiration, employer, dietary_restrictions, secondary_contact_fname, secondary_contact_lname, secondary_contact_mname, secondary_contact_title, secondary_contact_suffix, secondary_contact_job_title, emergency_contact_name, emergency_contact_phone, emergency_contact_notes, is_company) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

Here is the important part of the stack trace:

org.hibernate.AssertionFailure: null id in org.XXXXXXX.Contact entry (don't flush the Session after an exception occurs)

I have tried setting the unsaved-value to "0" and "-1" and sending them over the wire. Any ideas on what I am doing wrong?

+2  A: 

Hey,

You have to remember that Hibernate is a persistence layer and needs to be able to keep track of where an object is in the database. So when it does an insert, it actually will need to query the auto-increment counter to see what the next ID should be. It then inserts the ID into the object and inserts the object into the database. So for hibernate to do in insert, it uses needs to do a select first (unless you're using some sort of GUID generated by the application). When using mySQL auto-increment, use the "identity" generator.

Explanation of the various generators:

http://www.roseindia.net/hibernate/hibernateidgeneratorelement.shtml

A hibernate XML code snippet:

 <id name="id" type="long" unsaved-value="null" >
    <column name="uid" not-null="true"/>
    <generator class="identity"/>
 </id>
davidemm
Changing the generator class worked. Through the link provided I was able to fix my problem. I ended up suing increment rather than identity. Thanks!
Ryan H