0

I have a MySQL DB which is being accessed by 2 Java processes from 2 different hosts using the Hibernate framework. As I want the DB to be consistent upon access from the processes on both the host, I made the primary key of the Table I'm accessing as auto_increment in the underlying database using SQL (Although I wanted a solution to make is auto_increment from Hibernate, I wasn't able to get it to work.) Now my problem is that hibernate caches objects in memory and when a persist operation is done, I'm getting duplicate primary key error, upon concurrent access. My understanding is that it is due to Hibernate using the primary key numbers based on the highest primary key it read during the last read. But since another process could have updated the DB, the latest primary key value with hibernate is stale and ends up using an existing(updated by the other process) primary key.

I would like to know if there is a way to avoid persisting the primary key(as it results in duplication) field from hibernate and allow the DB to determine it using auto_increment.

Fayaz Ahmed
  • 953
  • 1
  • 9
  • 23

1 Answers1

0

You should change your generation strategy to sequence or guid (depending on your database). These are safe and better because the id generation will happen inside the database.

Refer to this StackOverflow Answer: How to choose the id generation strategy when using JPA and Hibernate

Community
  • 1
  • 1
Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71
  • also add version or timestamp to your entities .. to enable optimistic locking and avoid any concurrency issue – Zulfi Jun 28 '16 at 03:56