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?
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>
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With