I have a controller as follows:
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Transaction tx = null;
Session session = sessionFactory.openSession();
session.flush();
tx=session.beginTransaction();
List<Plane> allPlanes = session.createQuery("from Planes").list();
tx.commit();
session.close();
When I add a new record in the table through MySqlWorkBench GUI app, and hit this controller again, it doesn't pick up the latest record. Only after I restart tomcat will the new record be picked up. I've tried setting various caching options within the config file for hibernate and nothing seems to make a difference. How can I ensure that no matter where the data is updated that this query will always return a fresh copy of the data in the database?
You can't make changes to the database outside of JPA and expect JPA to know about it.
There is a way to get hibernate to reset, but you will have to have your database trigger and then send message over the network, or call a function manually.
On my systems, I have a manual reset that I invoke from a menu when I need to go behind the scenes and update the database directly, without restarting the JVM.
em.getEntityManagerFactory().getCache().evictAll();
How can I ensure that no matter where the data is updated that this query will always return a fresh copy of the data in the database?
As you limit your question to this query , you don't need to change your configuration or globally evict all caches.
Before invokation of org.hibernate.query.Query.list()
simply invoke org.hibernate.query.Query.setCacheable(boolean)
with false
as argument for this query .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.