Reputation: 502
What I am working on right now requires the id (primary key) can be defined by the user on creating the record. However, as long as the id is provided, the save process becomes an update instead of insert.
Details as below, Technology: Groovy and Grails 1, Hibernate 3. Configuration: myclass.hbm.xml, I changed the id from
<id name="id" type="long" column="MY_ID" unsaved-value="null">
<generator class="sequence">
<param name="sequence">my_id_seq</param>
</generator>
</id>
to
<id name="id" type="long" column="MY_ID" unsaved-value="null">
<generator class="assigned">
</generator>
</id>
In the model class MyClass.groovy, I explicitly define the id as an property.
I have show_sql true. When the id is sequenced and I leave it auto-geneated, I can see insert statement printed out and record is found in the table. After the id become assigned and I assign (a new) one, it always print update.
Hope the information is clear and sufficient for help..
Upvotes: 1
Views: 442
Reputation: 121
you can use like this if you want.
<hibernate-mapping package="your-package">
<class name="Sequence" table="sequence">
<id name="id" type="long">
<generator class="increment"/>
In above case by default it will start from 1. Sequence:-For start sequence from 1 but you can specify any other number as well at the time of table creation.
Upvotes: 0
Reputation: 23562
Do not specify unsaved-value
attributes for assigned
id generators.
By default, unsaved-value
for assigned
id generator is undefined
and I don't recommend to change it. In your current id generator definition you are basically telling Hibernate that objects which have null
value in the id field are transient and the others are not. Hence the objects with non-null ids would never be considered transient.
Upvotes: 1