1

we're having a problem with hibernate performing INSERT query instead of UPDATE.

Background: we're running two long-term transactions in parallel, modifying the same table. While the transactions run, we use entityManager.merge(), but only flush to the db in the end, right before the commit.
So, transaction a commits successfully. Few minutes later, when transaction b tries to flush, it fails with ConstraintViolationException caused by having duplicate keys in the common table.
We assume that when transaction b merges, transaction a hasn't commited yet, the entity hasn't been written to the DB and so an INSERT query is created. However, transaction a commits before transaction b and inserts the entity to the DB, so at that moment we need to change the query in transaction b to update.

Any suggestions?

Daniel Taub
  • 5,133
  • 7
  • 42
  • 72

1 Answers1

0

Since you are using Hibernate instead of pure JPA, you can use Session#saveOrUpdate. You can get access to the Hibernate session with Session session = entityManager.unwrap(Session.class);

Frank Riccobono
  • 1,043
  • 6
  • 13
  • thank you, but i suppose that that what merge doing, no? – Daniel Taub Jul 28 '19 at 15:58
  • They behave slightly differently. For `merge` to work the entityManager needs to know the object exists. It doesn't check the DB first. As an alternative to using the Hibernate session, see this answer: https://stackoverflow.com/a/36241661/1245752 – Frank Riccobono Jul 28 '19 at 16:49