sebi
sebi

Reputation: 41

JPA cache not invalidated

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?

Upvotes: 2

Views: 499

Answers (1)

Chris
Chris

Reputation: 21145

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.

Upvotes: 0

Related Questions