I am using Hibernate / JPA with mySQL, and due to obsolete reasons to createNativeQuery at some point. The application works with different servers using the same database, so you donβt need to cache at all, but it always shows the latest result. I mimic other servers by manually changing the value in the database editor, but after the change, it always gives old results.
As far as I know, I have to disable second level caching (not very important because I do not use any ORM objects), clear () any level 1 caching and disable mysql query caching (already done at the database level). Where do I fail or what do I forget? It drives me crazy.
init (): start of servlet
entityFactory = Persistence.createEntityManagerFactory("persistence-id");
getEntityManager (): start of each request
destroyEntityManager(); // just in case entityFactory.getCache().evictAll(); entityManager = entityFactory.createEntityManager(); entityManager.setProperty("javax.persistence.cache.storeMode", CacheStoreMode.BYPASS); entityManager.clear(); // just in case
destroyEntityManager (): end of each request
if (entityManager != null) { if (entityManager.getTransaction().isActive()) { entityManager.flush(); entityManager.getTransaction().commit(); } entityManager.clear(); if (entityManager.isOpen()) { entityManager.close(); } entityManager = null; }
destroy (): end of servlet
destroyEntityManager(); if (entityFactory != null) { entityFactory.close(); }
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0"> <persistence-unit name="WallMountBackOffice-PU"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <class>...</class> <class>...</class> <properties> <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" /> <property name="hibernate.connection.url" value="jdbc:mysql://localhost/ourschema" /> <property name="hibernate.connection.username" value="root" /> <property name="hibernate.connection.password" value="" /> <property name="hibernate.connection.pool_size" value="10" /> <property name="hibernate.connection.autocommit" value="false" /> <property name="hibernate.connection.release_mode" value="on_close" /> <property name="dialect" value="org.hibernate.dialect.MySQLDialect" /> <property name="hibernate.cache.use_second_level_cache" value="false" /> <property name="hibernate.cache.use_query_cache" value="false" /> <property name="javax.persistence.sharedCache.mode" value="NONE" /> <property name="org.hibernate.cacheable" value="false" /> </properties> </persistence-unit>
Code that executes "select ...":
... Query jpaQuery = entityManager.createQuery(query); entityManager.getTransaction().begin(); jpaQuery.executeUpdate(); entityManager.getTransaction().commit();