Issue:
In a JPA transaction, Updating of the same entity is split into two separate UPDATE SQL statement execution.
Reason:
- Some properties of an entity is updated in a transaction.
- Then there is a db query to retrieve some data.
- This query execution cause the above entity modification to flush to the db. (Due to the JPA implementation).
- This cause the execution of the first UPDATE SQL statement.
- Update another set of properties of the same entity.
- At the next flush event (at the end of TX or execution of another query), The execution of the second UPDATE SQL statement on the same record executed for the last change..
// Start modifying bankAccount entity
bankAccount.setName(name);
// Execute a Query which causes flush
List<PaymentOrganization> paymentOrganizations = paymentOrganizationFacade.getAllOrganizations();
// modify another attribute of same entity
bankAccount.setPaymentOrganizations(paymentOrganizations);
Solution:
Do not put any query execution in between the modifications of different attributes of the same entity object.E.g:
Move the query before starting the modification of the entity.
List<PaymentOrganization> paymentOrganizations = paymentOrganizationFacade.getAllOrganizations();
bankAccount.setName(name);
bankAccount.setPaymentOrganizations(paymentOrganizations);