强制 Hibernate 读取数据库而不是 return 缓存的实体

Force Hibernate to read database and not return cached entity

我正在为我的 Web 应用程序使用 Hibernate 和 Spring。

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

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

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

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

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

session.refresh(entity)entityManager.refresh(entity)(如果您使用 JPA)将为您提供来自数据库的新数据。

在新事务中进行读取。

例如:

...
MyDTO myDTO = fetchMyDTOById(daoId);
...
@Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
private MyDTO fetchMyDTOById(Long dtoId) {
    return repository.findById(dtoId);
}
  • 调用刷新实体session.refresh(entity)

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

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

请调用EntityManger.clear()方法,然后根据您的要求调用repository.find()或repository.findOne()select从数据库更新数据.

@PersistentContext EntityManager em;
@Autowired EntityReporisitory rep;
....
....
@Transactional
public void method(){
....
....
em.clear();// This line will clear the current value of entity
Entity e = rep.find(example);// In this line data will be loaded freshly from DB
....
....
}