Home Spring test updates locally read JPA entity during transaction
Reply: 1

Spring test updates locally read JPA entity during transaction

wrapperapps
1#
wrapperapps Published in 2018-01-12 22:48:46Z

This question already has an answer here:

  • How do you test Spring @Transactional without just hitting hibernate level 1 cache or doing manual session flush? 2 answers

I have a Spring integrated test that is wrapped in @Transactional. The Hibernate/JPA database interface extends JpaRepository and uses PESSIMISTIC_READ and PESSIMISTIC_WRITE locks on its functions. Within the test, the following steps occur:

  1. An @Entity object is read from the repo.
  2. The target function runs, which updates and writes that same @Entity to the repo inside another @Service-level transaction.
  3. That @Entity object is again read from the repo and compared to the first object.

The problem is that after writing in step 2, the first @Entity object has actually been updated locally. When comparing the @Entity objects in step 3, both are equal instead of having expected "before and after" differences.

How is this "syncing" of local @Entity objects happening, and is this expected behavior?

wrapperapps
2#
wrapperapps Reply to 2018-01-13 04:54:58Z

After some research using the right terms (e.g. caching in persistence context), it appears to be expected as described here: https://vladmihalcea.com/how-does-hibernate-store-second-level-cache-entries/

A viable workaround would be to manually refresh the entity or separate the 2 reads into different transactions, as mentioned here: Force hibernate to read database and not returning cached entity

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.332218 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO