Abhishek Saxena
Abhishek Saxena

Reputation: 1

SpringData JPA is not refreshing or clear the cache, when table is updated from outside resource

I'm working on SpringBoot Jpa to interact with DB tables, in few of my JPA repository I am getting old version of JPA Entity(Not Updated) when other applications updated that particular database table from outside, JPA is not able to give updated dataset. I tried using EntityManager.clear(), entityManager.getEntityManagerFactory().getCache().evictAll(); but not of them working.

At the end, I had to create a new entityManager object from entityManagerFactory and run the native SQL to get the updated output. But this is not a good practice for my project as it makes my JPA dependent on Native SQL. So, please let me know if there is anything I am missing or should do to reflect the latest changes from my JPA repository at run time. Or is there any way from which I can run JPA repository from newly created entitymanager object?

 entityManager.getEntityManagerFactory().getCache().evictAll(); //Autowired from persistenceContext
        entityManager.clear();
        EntityManager em=emf.createEntityManager();

Upvotes: 0

Views: 1080

Answers (2)

Sanket Patel
Sanket Patel

Reputation: 259

Try adding @Transactional annotation to the Service.

Also, make sure you're having a single entity instance.

Upvotes: 1

David
David

Reputation: 80

I think you should add the bellow code:

entityManager.flush();

Upvotes: 0

Related Questions