Home One EntityManager doesn't see updates done by another EntityManager
Reply: 0

One EntityManager doesn't see updates done by another EntityManager

user1278
1#
user1278 Published in May 22, 2018, 9:24 pm

I'm using two EntityManager instances in standalone application with RESOURCE_LOCAL transaction type. I perform such operations:

  • Save entity using first EntityManager (em1)
  • Update entity using second EntityManager (em2)
  • Read entity using first EntityManager (em1)

The problem is that em1 on the 3rd step doesn't see updates done by em2.

EntityManagerFactory emf = Persistence.createEntityManagerFactory("test");

// Step 1: create entity
EntityManager em1 = emf.createEntityManager();
em1.getTransaction().begin();
Article article = new Article("article_1");
em1.persist(article);
em1.getTransaction().commit();

// Step 2: update entity
EntityManager em2 = emf.createEntityManager();
em2.getTransaction().begin();
Article articleForUpdate = em2.find(Article.class, 1L);
articleForUpdate.setName("updated article_1");
em2.persist(articleForUpdate);
em2.getTransaction().commit();

// Step 3: read updated entity
em1.getTransaction().begin();
Article updatedArticle = em1.find(Article.class, 1L);
em1.getTransaction().commit();

log.info("updated entity: {}", updatedArticle); // logs stale data

em1.close();
em2.close();
emf.close();

Can anyone explain why em1 reads stale data?

You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO