Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable completely Hibernate caching? (with Spring 3, Hibernate with annotations)

Tags:

hibernate

My java app queries a MySQL server every 10 seconds. I manually insert a new row into a table. Hibernate can't find it.

When I manually remove a row, Hibernate shows that this row exists. I suppose that is because of Hibernate caching. Is there any way to disable it at all?

like image 470
gennad Avatar asked Nov 15 '10 17:11

gennad


2 Answers

Do you mean the first-level cache or the second-level cache? Having a Hibernate second-level cache such as Ehcache that caches entities that correspond to the rows in the same table that you modify manually could cause the behaviour that you describe. The first-level cache would not cause this behaviour, and I don't think you can disable it, anyway.

To disable the Hibernate second-level cache, remove from the Hibernate configuration file, hibernate-cfg.xml, all lines that refer to the second-level cache. For example:

<!-- Enable the second-level cache  -->
<property name="hibernate.cache.provider_class">
    net.sf.ehcache.hibernate.EhCacheProvider
</property>
<property name="hibernate.cache.region.factory_class">
    net.sf.ehcache.hibernate.EhCacheRegionFactory
</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_structured_entries">true</property>     
<property name="hibernate.cache.generate_statistics">true</property>
like image 197
Derek Mahar Avatar answered Nov 18 '22 22:11

Derek Mahar


In order to "try" to disable the first-level cache, I evict it everytime an EntityManager is requested. worked for me ;)

public EntityManager getEntityManager(){
        if( emf == null ){
            if (parameters == null) {
                emf = Persistence.createEntityManagerFactory(persistenceUnitName);
            } else {
                emf = Persistence.createEntityManagerFactory(persistenceUnitName, parameters);
            }
        } else {
            emf.getCache().evictAll();
        }

        EntityManager em = emf.createEntityManager();
        return em;
    }
like image 2
hamilton.lima Avatar answered Nov 18 '22 22:11

hamilton.lima