timbotoolman
timbotoolman

Reputation: 65

JPA / Hibernate / MS SQL Server not returning generated id value

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?

Upvotes: 4

Views: 8149

Answers (3)

javaauthority
javaauthority

Reputation: 429

I had a similar issue that I troubleshooted and this worked for me:

em.persist({ENTITY_TO_PERSIST});
em.flush();
em.refresh({ENTITY_TO_PERSIST});

The refresh() method did the trick.

NOTE: In my answer, I assumed that your database table is properly set up with its Identity Specification set to 'yes' for the column in question.

Upvotes: 2

Pascal Thivent
Pascal Thivent

Reputation: 570345

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.

Upvotes: 0

Javid Jamae
Javid Jamae

Reputation: 9009

Use a capital "I" integer.

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

Upvotes: 0

Related Questions