简体   繁体   English

休眠查询不返回新数据

[英]Hibernate query not returning fresh data

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. 当我通过My​​SqlWorkBench GUI应用程序在表中添加新记录并再次点击该控制器时,它不会获取最新记录。 Only after I restart tomcat will the new record be picked up. 只有在重新启动tomcat之后,新记录才会被拾取。 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. 您不能在JPA之外对数据库进行更改,并且希望JPA知道它。

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. 在我的系统上,当我需要在后台进行操作并直接更新数据库而无需重新启动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 . 在调用org.hibernate.query.Query.list()之前,只需使用false作为此查询的参数调用org.hibernate.query.Query.setCacheable(boolean)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM