views:

80

answers:

2

Hello, I have a Java object with a field that needs to be auto-incremented in the database. This field is not a primary key, just a field that needs to be auto-incremented.

My question is what value I need to set this field in my Java object before doing a session.save(Object)? Do I have to set it to NULL?

How would the Hibernate mapping look for this field? This is what I have but its not working:

<property name="reportNum" type="java.lang.Long">
 <column name="REPORTNUM"/>
 <generator class="increment"/>
</property>

Also the application needs to support both MySQL and SQL Server.

thanks in advance.

A: 

You can't use a <generator> for a non id field. I can think of two possible solutions here.

Option 1

Have the property generated by the database (either using an auto-increment column1 or a trigger) and map it as generated property (see 5.6. Generated properties):

<property name="reportNum" type="java.lang.Long" generated="insert">
  <column name="REPORTNUM"/>
</property>

This tells Hibernate that the given property value is generated on insert (and Hibernate will read it after the insert to value the entity).

Option 2

Create an entity with only an ID attribute. When you need a new value you simply create a new instance and save it to the database. Then, you set the generated ID in your entity.

1 DISCLAIMER: I didn't check if this is possible for a non pk column.

Pascal Thivent
Thank you for pointing that generated="insert" attribute. I will include that in my hibernate mapping file.
Marquinio
+1  A: 

I would try and keep it as simple as possible and just mark the property with the insert=false, update=false attributes. I've ran into trouble before using the @Generated annotation with named queries, but insert/update=false has always worked as advertised.

Matt Brock