开发者

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

开发者 https://www.devze.com 2023-01-12 11:35 出处:网络
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:

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?


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.


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.


Use a capital "I" integer.

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

精彩评论

暂无评论...
验证码 换一张
取 消