1

I have the code:

public EntityManager getEntityManager() {

EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-app");
EntityManager em = emf.createEntityManager();

return em;

}
for (...) {
  EntityManager em = getEntityManager();
 
  ...creating myEntity
 
  for (...) {
    em.getTransaction().begin();
    entityManager.persist(myEntity);
    em.getTransaction().commit();
  }
 
}

The problem: I run this code 8 AM , and I see records on database. When I run the code 9 hours later the records from 8AM are deleted

Could you please tell me if I am right:

  • Even though there is always different reference to EM , there is only one persistence context.
  • By default, managed entity objects that have not been modified or removed during a transaction are held in the persistence context by weak references
  • During these 9 hours garbage collector removed previous entities
  • EM did not "see" entites and deleteded records from DB

Is this solution correct?

add => em.clear();

for (...) {
  EntityManager em = getEntityManager();
 
  ...creating myEntity
 
  for (...) {
    em.getTransaction().begin();
    entityManager.persist(myEntity);
    em.getTransaction().commit();
  }
 
  em.clear(); 
}

I found this =

http://wiki.eclipse.org/EclipseLink/FAQ/How_to_disable_the_shared_cache%3F

So, my solution is going to be OK when i add this =

<property name="eclipselink.cache.shared.default" value="false"/> 
newuser123123
  • 87
  • 1
  • 1
  • 5
  • I think you are chasing the wrong rabbit, down the wrong hole. – Scary Wombat Jun 28 '22 at 23:49
  • Are you keeping your EntityManager open? – Scary Wombat Jun 29 '22 at 00:30
  • I am creating a new EM every call – newuser123123 Jun 29 '22 at 00:31
  • can you please see what I wrote about Eclipse link. Adding that property is sufficient to solve the problem ? – newuser123123 Jun 29 '22 at 00:33
  • > I am creating a new EM every call - I can see that, but are you closing the existing EM? – Scary Wombat Jun 29 '22 at 00:36
  • No , so, close it also ? – newuser123123 Jun 29 '22 at 00:37
  • 1
    I think that the best practices are summarised here https://stackoverflow.com/questions/4543947/when-should-entitymanagerfactory-instance-be-created-opened/4544053#4544053 – Scary Wombat Jun 29 '22 at 00:43
  • You've left a lot out of your question, such as what is deleting records (if anything) after 8am. That EclipseLink has a second level cache is part of its documentation and a key feature that will benefit your applications performance. If you have external processes deleting records, it might be a pain, but put it another way; you've gone 9 hours without a database hit for entities, proven by them having already been removed. EclipseLink has many ways to manage this shared cache without outright disabling it: https://www.eclipse.org/eclipselink/documentation/2.7/solutions/scaling002.htm – Chris Jun 29 '22 at 16:21

0 Answers0