Java 强制 Hibernate 读取数据库而不返回缓存的实体

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27905148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 05:16:08  来源:igfitidea点击:

Force Hibernate to read database and not return cached entity

javaspringhibernatecaching

提问by Saif

I am using Hibernate and Spring for my web application.

我正在将 Hibernate 和 Spring 用于我的 Web 应用程序。

In database operation, Hibernate is caching entities and returning them in next request without reading the actual database. I know this will reduce the load on database and improve performance.

在数据库操作中,Hibernate 缓存实体并在不读取实际数据库的情况下在下一个请求中返回它们。我知道这将减少数据库的负载并提高性能。

But while this app still under construction, I need to load data from database in every request (testing reason).

但是当这个应用程序仍在建设中时,我需要在每个请求中从数据库加载数据(测试原因)。

Is there any way to force database read?

有没有办法强制读取数据库?

I became sure about the caching from this log4j message.

我从这个 log4j 消息中确定了缓存。

Returning cached instance of singleton bean 'HelloController'
DEBUG [http-bio-8080-exec-42] - Last-Modified value for [/myApp/../somePageId.html] is: -1

采纳答案by Predrag Maric

session.refresh(entity)or entityManager.refresh(entity)(if you use JPA) will give you fresh data from DB.

session.refresh(entity)或者entityManager.refresh(entity)(如果你使用 JPA)会给你来自 DB 的新数据。

回答by wild_nothing

Do the read within a new transaction.

在新事务中执行读取。

For example:

例如:

...
MyDTO myDTO = fetchMyDTOById(daoId);
...
@Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
private MyDTO fetchMyDTOById(Long dtoId) {
    return repository.findById(dtoId);
}

回答by Hatem Badawi

  • Call refresh entity session.refresh(entity)

    or

  • Open new session then call session2.get(EntityClass.class,id)it will pull the entity from the database

        Session session2=sessionFactory.openSession();                  
        EntityClass entity=(EntityClass) session2.get(EntityClass.class, id);
    
  • 调用刷新实体 session.refresh(entity)

    或者

  • 打开新会话然后调用session2.get(EntityClass.class,id)它将从数据库中提取实体

        Session session2=sessionFactory.openSession();                  
        EntityClass entity=(EntityClass) session2.get(EntityClass.class, id);