views:

307

answers:

2

I am using Hibernate entity manager 3.5.1-Final with MS SQL Server 2005 and trying to persist multiple new entities. My entity is annotationally configured thus:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

After calling

entityManager.persist(newEntity)

I do not see the generatedId set, it remains as 0. This causes the following exception when persisting the next new entity:

org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [x.y.z.MyEntity#0]

I can get round this by evicting the recently persisted entity from the cache before I persist the next entity, but this is not ideal. What do I need to do to update the object correctly after insert?

A: 

Use a capital "I" integer.

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
Javid Jamae
Doesn't seem to make a difference. Neither does flushing after each insert.
timbotoolman
So if you persist just one object, does it actually appear in the database? If so, have you overridden the equals and hashcode methods, are they perhaps returning the wrong values? Have you tried setting the annotations on the getId() instead of the field? Do you have getters and setters defined? Please provide us with more detail.
Javid Jamae
Also, are you using "auto_increment" on the id when you create the table? Create TABLE XXX (`id` int NOT NULL AUTO_INCREMENT, etc.)
Javid Jamae
I found the problem - this was a legacy table and I didn't realise there was an INSTEAD OF INSERT trigger on the table which was screwing up the @@IDENTITY value passed back to Hibernate.
timbotoolman
A: 

I do not see the generatedId set, it remains as 0.

The annotated code itself looks correct (you can use IDENTITY with long, short, integer types - and their respective wrapper types - and String). Now, the questions are:

  • are you really using an identity column on the db side (please show your table definition)?
  • what SQL statement does actually get performed (activate SQL logging)?
  • what happens if you execute the generated SQL in a SQL client?

I can get round this by evicting the recently persisted entity from the cache before I persist the next entity, but this is not ideal.

This is clearly not a solution. The generated id should get assigned to the persisted entity and any other behavior is unexpected. There is definitely a mismatch somewhere that need to be fixed. Please provide the requested informations.

Pascal Thivent
I found the problem - this was a legacy table and I didn't realise there was an INSTEAD OF INSERT trigger on the table which was screwing up the @@IDENTITY value passed back to Hibernate.
timbotoolman