2

I am developing an application using Eclipse IDE, EclipseLink, JPA and MySQL. During the initial launch of the app, I need to delete a table's content. However, after deletion the application, making a new connection, still reads the old data from the empty table. My initial approach was to create a new EntityManager each time an operation was performed.

    private EntityManager entityManager;

    public FacadeFactory() {
        entityManager = DBConnection.connect();
    }

After disabling the JPA caching, the problem was solved.

Due to performance issues, the EntityManager was changed to Singleton in order to open a only one connection to the database.

    private static FacadeFactory instance;
    private EntityManager entityManager;

    private FacadeFactory() {
        entityManager = DBConnection.connect();
    }

    public static FacadeFactory getInstance(){
        if(instance == null){
            instance = new FacadeFactory();
        }
        return instance;
    }

Now, I have the same problem as before even if the cache is still disabled. I tried to disable the caching both from persistence.xml and from code, but none of them works for me.

<property name="eclipselink.cache.shared.default" value="false"/>
entityManager.getEntityManagerFactory().getCache().evictAll();

Can anyone please help me?

sebi
  • 41
  • 6
  • What performance issues did you have with using new EntityManager when required? They should be light weight, the only major benefit I can see should be the added caching which you wanted disabled anyway. – Chris Jun 13 '14 at 12:55
  • @Chris, I noticed the program was running slightly slower when creating new EntityManagers each time. – sebi Jun 13 '14 at 13:55

1 Answers1

0

entityManager.getEntityManagerFactory().getCache().evictAll(); is clearing the shared cache, while eclipselink.cache.shared.default" value="false" also affects the shared cache. The shared cache is also known as a second level cache - the first being the cache used within the EntityManager itself to track managed entities. Because you are using a single EntityManager for everything, everything gets put in that first level cache.

Either you can create a new EntityManager as required, or you can occasionally call em.clear() to clear the cache in the EntityManager - detaching your entities.

Chris
  • 20,138
  • 2
  • 29
  • 43
  • Thanks @Chris! I solved the issue by calling em.refresh(entity) each time I was calling find() or findAll(). Which one (refresh or clear) do you think is better? – sebi Jun 13 '14 at 13:57
  • I would instead work on demarcating your EntityManager so that you can call clear occasionally to release resources. Calling clear or refresh on each and every find or query might cause performance issues, but it all depends on how you are using the app. – Chris Jun 13 '14 at 14:08