Force Hibernate to issue DELETEs prior to INSERTs to avoid unique constraint violations?
From the problem you described, it's not clear if you have an entity BondPayment
or if you have a Bond
linked directly to a Payment
. For now, I suppose you have the link between Payment
and Bond
through BondPayment
. In this case, Hibernate is doing the right thing, and you'll need to add some logic in your app to retrieve the link and remove it (or change it). Something like this:
bond.getBondPayment().setPayment(newPayment);
You are probably doing something like this:
BondPayment bondPayment = new BondPayment();bondPayment.setPayment(newPayment);bondPayment.setBond(bond);bond.setBondPayment(bondPayment);
In the first case, the BondPayment.id
is kept, and you are just changing the payment
for it. In the second case, it's a brand new BondPayment
, and it will conflict with an existing record in the database.
I said that Hibernate is doing the right thing because it threats BondPayment
as a "regular" entity, whose lifecycle is defined by your app. It's the same as having a User
with a unique constraint on login
, and you are trying to insert a second record with a duplicate login
. Hibernate will accept (it doesn't knows if the login
exists in the database) and your database will refuse.