Wednesday, March 23, 2016

JPA ISSUE - Execution of Double (or Multiple) UPDATE SQL Statements for the Updates done on the same Entity Object

Issue:


In a JPA transaction, Updating of the same entity is split into two separate UPDATE SQL statement execution.

Reason:


  1. Some properties of an entity is updated in a transaction.
  2. Then there is a db query to retrieve some data.
  3. 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.
  4. Update another set of properties of the same entity.
  5. 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..
E.g:
// 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);

No comments: