2

I have a spring boot app, a REST service is called inside this rest call two separate DB operations are done (Spring Data JPA is being used). First one updates some database tables and second one reads from the said tables and do some operations.

@GetMapping("/process")
public void process(){
   service1.updateValues();//updates the values
   service2.readValuesAndProcess();//reads those updated values and execute some logic and persist at the end
}

Now the problem is;

Second method doesn't seem to read the updated values that are updated in the first method and somehow reads the values before the update. Both these methods are @Transactional, Entities are @versioned and when a save operation is called ObjectOptimisticLockingFailureException is thrown.

In application.properties spring.jpa.open-in-view property is true, when i change it to false everything works as expected but i can't guarantee that i won't get a lazyInitializationException somewhere else.

I tried changing transactional methods propagation to REQUIRES_NEW and nothing changes.

YamYamm
  • 381
  • 1
  • 3
  • 12
  • 1
    How do you update the values in the updateValues() method? If you use spring.jpa.open-in-view = true, then in your request there is only one entity manager used for all your statements. So the objejct you save might not be reloaded from the database if it is still in the entity manager cache. BTW, spring.jpa.open-in-view = true is considered an anti-pattern. See this: https://stackoverflow.com/questions/30549489/what-is-this-spring-jpa-open-in-view-true-property-in-spring-boot – Matei Florescu Jun 11 '21 at 07:49
  • yes, we use spring.jpa.open-in-view = true, and your insight is correct. Entity is loaded via a @onetoone relationship from another entity and not being updated with save but with a custom hql query so first level cache is not being updated. So when second select is executed entity is being fetched from first level cache. – YamYamm Jun 15 '21 at 15:10
  • I had the same problem this week. Did you solve it and understand what happened? – Julien Berthoud Jul 14 '22 at 07:57

2 Answers2

0

How are you doing the update in updateValues? is the code thread safe for concurrent users? Lost updates might cause JPA to throw ObjectOptimisticLockingFailureException which is a good thing.

Please read this for more information about Optimistic Locking: Optimistic Locking in JPA | Baeldung.

Mo_-
  • 574
  • 3
  • 6
0

If updateValues() is annotated as @Transactional, it should work. At the end of updatevalues() the changes will be actually committed to database by spring

Nidhin Dev
  • 499
  • 5
  • 9